向儿童发送作为道具的功能

时间:2018-06-11 05:27:29

标签: reactjs select parent-child react-props

我有一个包含数据的类,我正在尝试将数据作为选项发送到子项中的select元素。

constructor(){
  super();
  this.state={
    value: [{key: '1', name: 'aaa'}, {key: '2', value: 'bbb'}],
  }
}
render(){
  const childProps = {
    getVal(){
    const val = this.state.value;
      return val.map((item) => {
        return (<option value={item.name}>{item.name}</option>);
      });
    }
  };

  return(
    //codes
    <Child {...childProps} />
  )
}

export const Child = ({ getVal }) => (
  <select>
    {getVal}
  </select>
);
Child.propTypes = {
  getVal: PropTypes.func,
};

但我没有在我的选择选项上获得任何值。它说未找到。 谁能帮我? 谢谢

3 个答案:

答案 0 :(得分:0)

试试这个,你没有调用这个函数。

export const Child = ({ getVal }) => (
  <select>
    {getVal()}
  </select>
);
Child.propTypes = {
  getVal: PropTypes.func,
};

答案 1 :(得分:0)

您可以尝试以下

 constructor(){
      super();
      this.state={
        value: [{key: '1', name: 'aaa'}, {key: '2', value: 'bbb'}],
      }
      this.getVal = this.bind.getVal(this)
    }
    render(){
        getVal(){
          const val = this.state.value;
          return val.map((item) => {
            return (<option value={item.name}>{item.name}</option>);
          });
        }


      return(
        //codes
        <Child getVal ={this.getVal} />
      )
    }

将getVal函数作为props

    export const Child (
     <select>
        {this.props.getVal}
     </select>
   );

答案 2 :(得分:0)

建议不要在render方法中添加这些函数。因为,每当调用渲染时,函数将再次构造。所以你可以这样做:

constructor(){
  super();
  this.state={
    value: [{key: '1', name: 'aaa'}, {key: '2', value: 'bbb'}],
  }
}

getVal = () => this.state.value.map((item) => (
   <Option value={item.name} key={item.name}>{item.name}</Option>
));

render(){    
  return(
    <Child getVal={() => this.getVal} />
  )
}

export const Child = ({ getVal }) => (
  <select>
    {getVal()}
  </select>
);
Child.propTypes = {
  getVal: PropTypes.func,
};