我的目标是通过单击组件performSearch ()
中的div
来调用函数Item
。 performSerach ()
函数位于另一个select ()
函数中。 select ()
函数将传递给Item
组件。在console.log中返回active = null
。
项目
class Items extends Component {
constructor (props) {
super(props);
this.state = {
items: [],
active: null,
abc: null
}
}
select = (id) => {
this.setState({
abc: id
})
this.performSearch(id);
}
componentDidMount() {
axios.get
axios({
url,
method: "GET",
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(res => {
this.setState({
items: res.data
});
})
.catch(error => {
console.log(error);
})
}
performSearch = (id) => {
axios.get
axios({
url: `https://app.com/api/v1/${id}`,
method: "GET",
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(res => {
this.setState({
active: res.data
});
})
.catch(error => {
console.log(error);
})
}
render () {
<div>
{this.state.items.map((item, index) =>
<Item
select={this.select}
/>
)}
</div>
}
}
项目
class Item extends Component {
render () {
return (
<div onClick={()=> this.props.select(this.props.item.id)}>
</div>
)
}
}
答案 0 :(得分:1)
render () {
<div>
{this.state.items.map((item, index) =>
<Item
select={this.select}
/>
)}
</div>
}
应将项目传递Item
组件:
render () {
<div>
{this.state.items.map((item, index) =>
<Item
select={this.select}
item={item}
key={index}
/>
)}
</div>
}
或者:
render () {
<div>
{this.state.items.map((item, index) =>
<Item
select={() => this.select(item.id)}
/>
)}
</div>
}