我知道如何映射对象数组,将每个对象的数据作为道具传递,以渲染组件数组,但是在此过程中如何传递事件处理程序?以下代码是我失败的尝试:
class App extends React.Component {
constructor() {
super();
this.state = {
allObjects: arrayOfObjects //arrayOfObjects is simply an imported array of object data
}
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
console.log("test"); // I'm merely trying to console log for this example
}
render() {
const objectsRendered = this.state.allObjects.map((i) => <myComponent key={i.id} i={i} onChange={this.handleChange}/>)
return(
<form>
{objectsRendered}
</form>
)
}
}
这是myComponent的代码:
function myComponent (props) {
return(
<div>
<input type="range" min="0" max="100" className="slider" id={props.i.id} onChange={props.handleChange}/>
</div>
)
}
答案 0 :(得分:3)
问题是您将名为 onChange 的道具传递给<myComponent />
,而不是名为 handleChange
因此,您应该改为这样做:
function myComponent (props) {
return(
<div>
<input type="range" min="0" max="100" className="slider" id={props.i.id} onChange={props.onChange}/>
</div>
)
}
——————————————
传递道具时,逻辑类似于变量声明:左值是道具名称,右值是您分配的道具值:
propName={propValue}