[英]ReactJS: lifting the parameter several levels up?
I want to upstream the key of the component on change. 我想在更改时将组件的键放在上游。 Ie, I write 即我写
onChange= {(e) => this.props.onChange(e, key)}
However, in my case this.props.onChange
also points in its turn to its props.onChange
function. 但是,在我的情况下, this.props.onChange
也指向其props.onChange
函数。 I've tried to define all the hierarchically "upper" assignments as onChange={this.props.onChange}
as well as onChange={(e,key) => this.props.onChange(e,key)}
, but nothing helps the fact that key
is undefined when it comes to the actual function body. 我试图将所有分层的“上层”分配定义为onChange={this.props.onChange}
以及onChange={(e,key) => this.props.onChange(e,key)}
,但什么也没有当涉及到实际的函数主体时,有助于定义key
未定义的事实。
Here's the full code of that what has to do with the peoblem: 这是与peoblem有关的完整代码:
handleValueChange = (e, key) => {
console.log('Event was on ' + key);
let currElemData = this.state.currentElementsData.slice();
currElemData[key] = {value: e.target.value};
this.setState({currentElementsData: currElemData});
};
addFilter = () => {
let activeFiltersNow = this.state.activeFilterElements.slice();
activeFiltersNow.push(<Filter key={this.state.filterCounter} onSelect={(e, key) => this.handleReferenceSelection(e, key)}
onChange={(e,key) =>this.handleValueChange(e, key)}/>);
let currElemData = this.state.currentElementsData.slice();
currElemData.push(InitialHelper.getInitialFilterData());
this.setState({activeFilterElements: activeFiltersNow, currentElementsData: currElemData, filterCounter: this.state.filterCounter++});
};
... ...
class Filter extends Component {
render() {
return <div className="filterContainer">
{this.props.isFirst? '':<FilterPrefix />}
<FilterReference onSelect={(e,key) => this.props.onSelect(e,key)} key={this.props.key}/>
<FilterAssignment />
<FilterValue onChange={(e,key) => this.props.onChange(e,key)} key={this.props.key}/>
<DeleteFilterButton />
</div>
}
}
... ...
class FilterValue extends Component{
render() {
return <input onChange={(e) => this.props.onChange(e,this.props.key)} key={this.props.key}/>
}
loadSuggestions(reference) {
}
}
I'm not quite sure what you are trying to do here, but I've noticed that you are falling for a pretty common ReactJs pitfall which is that: 我不太确定您要在这里做什么,但是我注意到您陷入了一个非常常见的ReactJs陷阱,那就是:
Keys serve as a hint to React but they don't get passed to your components. 密钥是React的提示,但不会传递给您的组件。 If you need the same value in your component, pass it explicitly as a prop with a different name 如果您在组件中需要相同的值,则将其作为道具使用其他名称显式传递
meaning that this.props.key
will always be undefined
. 意味着this.props.key
将始终是undefined
。 So, I'm afraid that all the instances in where you are using this.props.key
are not going to behave as you expect... 因此,恐怕您正在使用this.props.key
所有实例都不会按预期运行...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.