如何基于其他道具的值设置defaultProp值?

时间:2018-07-30 06:00:44

标签: reactjs react-proptypes

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

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

我怎样才能做到最好?

4 个答案:

答案 0 :(得分:4)

您可以在render方法中进行操作。

render() {
  const delay = this.props.trigger === 'hover' ? 100 : 0;
  // Your other props

  return (
    <SomeComponent delay={delay} />
    // or
    <div>
      {/*...something else, use your delay */}
    </div>
  );
}

答案 1 :(得分:2)

我宁愿建议您:

  • 将该变量作为实例变量存储在组件的类中
  • 评估它是否是状态变量而不是道具(或实例)

在两种情况下,您都应检查何时新道具到达组件并在需要时进行更新。

我要去状态变量并写这样的东西:

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() {
    ...
  }
}

通过这种方式,您可以在render方法中使用this.state.delay而不用担心确定其值。

答案 2 :(得分:1)

使用功能组件,您可以这样做:


d = {'col1': [25,20/99,30/101],
     'col2': [25,20/99,30/101],
     'col3': [25,20/99,30/101], 
     'col4': [25,39/99,11/101]
     }

df = pandas.DataFrame(data=d)

答案 3 :(得分:0)

我正面临着类似的问题,并且我发现本讨论中缺少基于method的解决方案,因此我正在写此答案

在两种情况下,您可能希望传递默认道具

情况1:当您要基于静态值选择defaultProps

情况2:当您要基于方法

选择defaultProps时

Case 1的解决方案

class Shape extends Component{
  static defaultProps = {
    colour: 'red',
  }
  render(){
   const {colour} = this.props;
   // Colour will always be 'red' if the parent does not pass it as a prop
   return <p>{colour}</p>;
  }
}

Case 2的解决方案

class Shape extends Component{
  calcArea = () => {
    console.log("Area is x");
  }
  render(){
   const {calcArea} = this.props;
   // calcArea will be evaluated from props then from the class method
   return <button onClick={calcArea || this.caclArea}></button>;
  }
}