将多个参数从子道具传递给父方法

时间:2018-09-26 10:42:20

标签: javascript reactjs redux react-redux

我是新来响应js的人。在这里,我想做的是,我有一个类似于以下内容的父组件:

onchange(event) {
        console.log("function will be callled", event.target.value, event.target.id);


     { (this.props.lowData) && this.props.lowData.Low.length > 0 && this.props.lowData.Low.map(data => (
                        <LowRow technologies={this.state.technologies} onChange={this.onchange.bind(this)} data={data} key={data.id} />
                    ))}

这里有一个onchnage方法作为道具传递给子元素,即:

<select className="selectpicker btn btn-labeled btn-start selectId techDrop  margin-left-10" onChange={props.onChange}>
                    <option disabled selected value>None Selected</option>
                    {props.technologies && <Select techData={props.technologies} options={props.technologyName} />}
                </select>

所以,现在我要做的是,当用户更改时,在孩子中:

onChange={props.onChange}

这在父元素中被调用,所以在这里我也想像这样传递另一个参数:

onChange = {props.onChange, props.id}so that Parent will get one Id as well, But its not working . And also I tried with the `props.onChange(props.id)` But no luck. Can any one help me with this ?

2 个答案:

答案 0 :(得分:0)

父项 year 2016 2017 diff area month A 1 10.0 0.0 -10.0 3 0.0 50.0 50.0 B 2 12.0 0.0 -12.0 4 0.0 52.0 52.0 函数将在第二个参数中接收onchange

id

从孩子那里打来电话时,您是这样打电话的。

onchange(event, id) {
    console.log("function will be callled", event.target.value, id);
}

答案 1 :(得分:0)

不建议您直接在render中绑定功能。因为当您直接在渲染中绑定函数时,由于多种原因(例如setState,接收到新道具等),您的组件将进行渲染,因此每次渲染时,它将在webpack生成的捆绑文件中创建一个新函数,因此文件大小变大。所以总是在构造函数中绑定

现在关于您的问题。直接在渲染中进行映射,并将onChange作为道具传递到LowRow组件。您需要执行以下操作,以将函数作为道具传递,并在子组件中向其发送参数,并在父组件中对其进行访问。这个概念在react中称为回调。

每当您在循环中生成jsx元素时,别忘了为父jsx元素添加密钥。密钥应该是数据中的唯一ID。如果您的数据不包含唯一ID,则将索引作为键传递,例如 key = {“ key” + index}

constructor(props){
   super(props);
   this.onChange = this.onChange.bind(this);
}

onChange(event, id) {
    console.log("test", event, id);
 }

render(){
   const { lowData } = this.props;
   return(
     <div>
        {this.props.lowData && this.props.lowData.Low.map(data => (
             <LowRow key={data.id} technologies={this.state.technologies} onChange={this.onChange} data={data} key={data.id} />
         ))}
     </div>
   )
}

选择onChange

这里不确定您要传递什么ID。但您可以像下面的代码一样传递参数

<select className="selectpicker btn btn-labeled btn-start selectId techDrop  margin-left-10" onChange={e  => props.onChange(e, id)}>
                    <option disabled selected value>None Selected</option>
                    {props.technologies && <Select techData={props.technologies} options={props.technologyName} />}
                </select>