React - 将道具传递给子onClick [英] React - Passing props to child onClick
问题描述
我有一个从Dropbox中提取的图像和标题索引。我的目标是能够点击一个标题并加载一个特定的项目,但是现在我只是试图将点击标题的数据传递给一个组件。
I have an index of images and titles I am pulling in from Dropbox. I aim to be able to click on a title and load a specific project, but right now I'm simply trying to get to grips with passing the data of a clicked title to the a component.
我看过React教程,文档&其他类似的问题在这里(并且我担心这将被视为一个重复的问题),但我似乎无法找到一种方法来传递被点击的特定标题。我目前收到错误:无法读取未定义的属性'title'。
I've looked at the React tutorial, the documentation & other similar questions on here (& am concerned this will be treated as a duplicate question), but I can't seem to figure out a way of passing the specific title that is clicked. I'm currently getting the error: Cannot read property 'title' of undefined.
我已成功通过以下方式提取特定标题console.log&用所有标题填充了ProjectTitle组件,但我对这个看似简单的障碍感到困惑。
I've managed to pull out the specific title via console.log & filled the ProjectTitle component with all of the titles but am stumped at this seemingly simple hurdle.
谢谢
class ProjectTitle extends React.Component{
render() {
return <h1>{this.props.title}</h1>;
}
}
class Index extends React.Component {
constructor(){
super();
this.state = {
imageSource: [],
imageTitles: [],
}
}
componentWillMount(){
…
}
render(){
if(!this.state.imageSource.length)
return null;
let titles = this.state.imageTitles.map((el, i) => <p>{el}</p>)
let images = this.state.imageSource.map((el, i) =>
<div className="imageContainer">
<img key={i} className='images' src={el}/>
<div className="imageTitle" onClick={() =>
ProjectTitle.props.title(titles[i].props.children)}>{titles[i]}
</div>
</div>
)
return (
<div className="wrapper">
{images}
<ProjectTitle />
</div>
);
}
}
推荐答案
一般来说在这种情况下,你想要遵循这样的结构:
Generally in a situation like this, you want to follow this structure:
- 点击事件处理程序设置一个状态属性,如
activeTitle
到被点击的ID。 - 需要设置其支柱的元素(
ProjectTitle
)获取来自它的父状态(索引
)。
- Click event handler sets a state property like
activeTitle
to the id that was clicked. - The element whose prop needs to be set (
ProjectTitle
) gets it from it's parent state (Index
).
对代码的更改可能看起来像:
The changes to your code might look something like:
// in Index constructor
this.state = {
// stuff you already have...
activeTitle: null
}
this.handleItemClick = this.handleItemClick.bind(this);
// in Index
handleItemClick(title) {
this.setState({activeTitle: title});
}
// in Index.render() in the loop
// you might have you add some code to get titles[i]
<div className="imageTitle" onClick={() => this.handleItemClick(titles[i])}></div>
// in Index.render() return statement
<ProjectTitle title={this.state.activeTitle} />
这篇关于React - 将道具传递给子onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!