如何在react.js中接受条件属性
下面是我的搜索组件,我希望InputGroup具有一个 onSubmit 属性(如果传递了onSubmit函数)和一个 onChange 属性(如果传递了onChange函数)
class QueryBar extends PureComponent {
render() {
const { placeholder, leftIcon, onSubmit, onChange, width } = this.props;
return (
<form
style={{ width }}
onSubmit={e => {
e.preventDefault();
onSubmit(e.target[0].value);
}}
>
<InputGroup
placeholder={placeholder}
width={width}
leftIcon="search"
rightElement={
<Button
type="submit"
icon={leftIcon}
minimal={true}
intent={Intent.PRIMARY}
/>
}
/>
</form>
);
}
}
QueryBar.propTypes = {
width: PropTypes.number,
placeholder: PropTypes.string,
leftIcon: PropTypes.oneOfType(['string', 'element']),
onSubmit: PropTypes.func
};
QueryBar.defaultProps = {
placeholder: 'Search...',
leftIcon: 'arrow-right',
width: 360
};
export default QueryBar;
发布于 2019-07-18 01:08:47
jsx元素也可以接受对象。初始化包含这两种情况的信息的对象,然后添加一个条件,如果函数存在于传入的道具中。
render() {
const { placeholder, leftIcon, onSubmit, onChange, width } = this.props;
const inputGroupProps = {
placeholder,
width,
leftIcon: 'search',
rightElement: (
<Button
type="submit"
icon={leftIcon}
minimal={true}
intent={Intent.PRIMARY}
/>
)
}
if (onChange) {
inputGroupProps.onChange = onChange
}
if (onSubmit) {
inputGroupProps.onSubmit = onSubmit
}
return (
<form
style={{ width }}
onSubmit={e => {
e.preventDefault();
onSubmit(e.target[0].value);
}}
>
<InputGroup {...inputGroupProps} />
</form>
);
}
虽然我不推荐这样做,但从技术上来说,添加两者都是可以的,因为一个不是从父节点传入,而是由非结构化结构传入的道具将是undefined
。我不推荐这样做,因为它没有表现力,将来可能会让你感到困惑。
<InputGroup
placeholder={placeholder}
width={width}
leftIcon="search"
rightElement={
<Button
type="submit"
icon={leftIcon}
minimal={true}
intent={Intent.PRIMARY}
/>
}
onChange={onChange} // will be undefined and have no behavior if parent does not pass an onChange prop
onSubmit={onSubmit} // same for this one
/>
发布于 2019-07-18 00:20:33
如果不存在,则可以传递null,即:
<InputGroup
placeholder={placeholder}
width={width}
leftIcon="search"
onChange={onChangeFn?onChangeFn:null}
onSubmit={onSubmitFn ? onSubmitFn : null}
rightElement={
<Button
type="submit"
icon={leftIcon}
minimal={true}
intent={Intent.PRIMARY}
/>
}
/>
它将确保函数是否存在,然后调用函数,否则就什么都不会。
发布于 2019-07-18 01:06:52
我会这么做:
其思想是有一个对象optionalProps
,一个可能的条件属性的空对象,当一个属性存在时,我们将它添加到对象中,然后,在InputGroup
组件中,我们将它作为{...optionalProps}
应用,它将提取任何添加到对象的属性,如果为null,则不返回任何返回值。
我们可以采用另一种方法:onChange={onChange && onChange}
但是,请注意,这将返回false
作为onChange
不存在的情况下的值。
render() {
const { placeholder, leftIcon, onSubmit, onChange, width } = this.props;
let optionalProps = {};
if(onChange){
optionalProps['onChange'] = onChange;
}
if(onSubmit){
optionalProps['onSubmit'] = onSubmit;
}
return (
<form
style={{ width }}
onSubmit={e => {
e.preventDefault();
onSubmit(e.target[0].value);
}}
>
<InputGroup
placeholder={placeholder}
width={width}
leftIcon="search"
{...optionalProps}
rightElement={
<Button
type="submit"
icon={leftIcon}
minimal={true}
intent={Intent.PRIMARY}
/>
}
/>
</form>
);
}
https://stackoverflow.com/questions/57090000
复制