如何在react.js中接受条件属性
下面是我的搜索组件,如果传递了 onSubmit 函数,我希望 InputGroup 有一个 onSubmit 属性;如果传递了 onChange 函数,我希望 InputGroup 有一个 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;
最佳答案
jsx 元素也可以接受对象。初始化一个包含这两种情况信息的对象,然后添加一个条件来添加一个函数(如果传入的 props 中存在该函数)。
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>
);
}
虽然我不建议这样做,但添加两者在技术上是可以的,因为不是从父级传入而是解构的 prop 将是未定义
。我不推荐这样做,因为它缺乏表达力,并且将来可能会让您感到困惑
<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
/>
关于javascript - React js 中的条件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090000/