【发布时间】:2019-04-07 22:44:57
【问题描述】:
我有一个问题 - 我需要从子组件更改父组件的状态。我尝试了带有道具的标准变体,但对我来说没有帮助。
这是父组件的代码:
class ThemesBlock extends React.Component {
constructor(props){
super(props);
this.state = {
currentThemeId: 0
}
}
changeState(n){
this.setState({currentThemeId: n})
}
render() {
let { data } = this.props;
return (
data.map(function (item) {
return <Theme key={item.id} data={item} changeState=
{item.changeState}/>
})
)
}
}
这是我的子组件代码:
class Theme extends React.Component {
constructor(props){
super(props);
this.changeState = this.props.changeState.bind(this);
}
render() {
const { id, themename } = this.props.data;
const link = '#themespeakers' + id;
return (
<li><a href={link} onClick={() => this.changeState(id)}
className="theme">{themename}</a></li>
)
}
}
【问题讨论】:
标签: javascript reactjs