代码之家  ›  专栏  ›  技术社区  ›  mohsinulhaq

如何根据其他属性的值设置默认属性值?

  •  6
  • mohsinulhaq  · 技术社区  · 6 年前

    我有一个组件,其中一个属性的默认值取决于另一个属性的值(默认值或用户提供的值)。我们无法执行以下操作,因为我们无法访问 this :

    static defaultProps = {
        delay: this.props.trigger === 'hover' ? 100 : 0,
        trigger: 'hover'
    };
    

    我怎样才能做到最好?

    2 回复  |  直到 6 年前
        1
  •  2
  •   LucioB    6 年前

    class MyComponent extends React.Component {
      static propTypes = {
        trigger: PropTypes.string,
      }
    
      static defaultProps = {
        trigger: 'hover',
      }
    
      constructor(props) {
        super(props);
        this.state = {
          delay: this.computeDelay(),
        }
      }
    
      componentWillReceiveProps(nextProps) {
        const { trigger: oldTrigger } = this.props;
        const { trigger } = nextProps;
        if (trigger !== oldTrigger) {
          this.setState({
            delay: this.computeDelay(),
          })
        }
      }
    
      computeDelay() {
        const { trigger } = this.props;
        return trigger === 'hover' ? 100 : 0;
      }
    
      render() {
        ...
      }
    }
    

    this.state.delay

        2
  •  4
  •   Anthony Liu    6 年前

    render() {
      const delay = this.props.trigger === 'hover' ? 100 : 0;
      // Your other props
    
      return (
        <SomeComponent delay={delay} />
        // or
        <div>
          {/*...something else, use your delay */}
        </div>
      );
    }