我试图将一个简单的列表从父组件传递到一组子组件,但我无法传递函数。我有一些行对行的东西,它是完全相同的该死的东西,但它不起作用。
有人看出出了什么问题吗?
这是我无法访问的父级中的函数(console.log 未触发):
setClassImage(name, image){
console.log('inside setClassImage');
var TitleArray = this.state.TitleArray;
TitleArray[0] = name;
var ImageArray = this.state.ImageArray;
ImageArray[0] = image;
this.setState({
characterModal: false,
equipmentModal: false,
TitleArray: TitleArray,
ImageArray: ImageArray
});
}
在父级中设置列表:
let listClasses;
if(this.state.classResults.length!=0){
listClasses = this.state.classResults.map((item,i) => {
return (
<ListClass key={i} classes={item} setClassImage={this.setClassImage.bind(this)}/>
);
});
}
在父级的渲染中:
<SelectorBox>
<ListBox>
{listClasses}
<br/>
</ListBox>
<SelectorButton onClick={(e)=>this.cancelChange(e)}>No Class</SelectorButton>
</SelectorBox>
在 child 中:
class ListClass extends Component{
constructor(props){
super(props);
this.state={
}
}
getImage(e){
e.preventDefault();
var self = this;
axios.post('http://localhost:5000/post2/characterimage', {
search: this.props.classes,
})
.then((response)=>{
console.log('response from the pixabay call ', response.data);
self.props.setClassImage(self.props.classes, response.data);
})
.catch(()=>{
console.log('hello axios error');
});
}
render(){
return(
<div>
<ItemContainer onClick={(e)=>this.getImage(e)}>
<p>
{this.props.classes}
</p>
</ItemContainer>
</div>
)
}
}
我可以看到 console.log('response from the pixabay call ', response.data);
并且它从后端的数据正确触发。但该函数没有被调用!这些奇怪命名的容器纯粹是为了样式化,所以假设它们都像 div 一样。
最佳答案
.then() 调用中的箭头函数会自动将 this 绑定(bind)到正确的上下文,因此您不需要执行 var self = this;但是,您确实需要在构造函数中绑定(bind) getImage 函数。或
将函数定义更新为:
....
getImage = (e) => {
e.preventDefault();
axios.post('http://localhost:5000/post2/characterimage', {
search: this.props.classes,
})
.then((response) => {
console.log('response from the pixabay call ', response.data);
this.props.setClassImage(this.props.classes, response.data);
})
.catch(()=>{
console.log('hello axios error');
});
}
....
}
否则,在构造函数中绑定(bind) getImage:
constructor(props){
super(props);
this.state = {};
this.getImage = this.getImage.bind(this);
}
关于javascript - 无法将函数从父级传递给 React 子级(通过列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893484/