React中的条件道具(仅接受2个道具中的1个)

时间:2019-07-04 06:42:53

标签: reactjs components react-props

我在react中有一个搜索栏组件,我想使用onSubmit道具或onChange道具,但不要同时使用它们。如何以最佳方式实施它?

我尝试使用if-else语句,但是代码对我来说看起来并不优雅。

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;

1 个答案:

答案 0 :(得分:0)

您可以使用三元运算符(?)代替if-else。

const { placeholder, leftIcon, onSubmit, onChange, width } = this.props;
const handleSubmit = onSubmit ? onSubmit : onChange;

并稍后使用相同的功能

<form
    style={{ width }}
    onSubmit={e => {
      e.preventDefault();
      handleSubmit(e.target[0].value);
    }}
>