我有一个带有对象的父组件,该对象包含一些表示范围的嵌套数组:
class ParentComponent extends React.Component {
constructor() {
super();
this.state = {
filters: {
rangeArray1: [0, 2000],
rangeArray2: [0, 5000]
// and many other similar nested arrays
}
}
}
//this gives TypeError: Cannot read property 'name' of undefined
//it works if there were nested objects instead of arrays
handleFilterChange = (e) => {
this.setState({
filters: {
...this.state.filters,
[e.target.name]: e.target.value,
}
})
}
//this works, but I need a method that handles all the arrays
handleFilterChange = (e) => {
this.setState({
filters: {
...this.state.filters,
rangeArray1: e.value,
}
})
}
//render method omitted
}
我还有一个更深的嵌套子组件,它使用范围滑块处理范围过滤:
class GrandchildComponent extends React.Component {
handleFilterChange = e => {
this.props.handleFilterChange && this.props.handleFilterChange(e)
};
render() {
return (
<div>
<p>Range1: {this.props.filters.rangeArray1[0]} - {this.props.filters.rangeArray1[1]}</p>
<Slider id="rangeArray1"
value={this.props.filters.rangeArray1}
name="rangeArray1"
onChange={this.handleFilterChange}/>
<p>Range2: {this.props.filters.rangeArray2[0]} - {this.props.filters.rangeArray2[1]}</p>
<Slider id="rangeArray2"
value={this.props.filters.rangeArray2}
name="rangeArray2"
onChange={this.handleFilterChange}/>
//and many other similar sliders
</div>
)
}
}
我有一种情况,用户使用范围滑块过滤一些数据,我试图使用回调方法将输入发送到我的父组件handleFilterChange
。我无法创建一个可以处理对象中所有数组的方法。我添加了一些我尝试过的示例代码,但是我的两个示例都有一些缺陷。
我正在使用 Primereact滑块组件