【发布时间】:2018-05-19 20:12:33
【问题描述】:
我是 React 新手。作为学习练习,我正在构建一个国际象棋应用程序
我想根据父级的状态更改子级的 DOM。目前,父组件的状态发生变化时,子组件没有变化。
父组件
class Game extends Component{
constructor(){
super();
this.state = {
game :{
board_position = { 'One' : ''}
}
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let p = this.state.game.board_position;
// some computations on p
p = { board_position : { 'One' : Math.random() } }
this.setState({
game : p
})
//this.forceUpdate(); // Just trying different methods to make it work
}
render(){
return(
<div onClick={(e) => this.handleClick(e) }>
<Piece {...this.state.game.board_position} />
</div>
)
}
}
子组件
Class Piece extends Component{
constructor(){
super(props);
this.state = {
clr : ''
}
}
componentWillMount(){
let c;
// some computations that change value of c based on props
if( typeof ( this.props.game.one) == number ){
c = 'Red'
} else {
c = 'Blue'
}
this.setState({
clr : c
})
}
render(){
return(
<span>{this.state.clr}</span>
)
}
}
在调用手柄点击方法时,游戏状态发生了变化。但是,看不到 Child 的后续变化。
谁能帮帮我?我哪里错了?
我不确定如何按照over here 的建议实现 ref。但是,我认为这不是一个好的解决方案。可能我在概念上有一些误解。
PS:请忽略任何语法错误。此代码是真实代码的精简版。 如果您想查看完整代码 - go over here
【问题讨论】:
-
这里发生了很多奇怪的事情。你不应该强制更新。设置状态应该为您处理。此外,永远不要直接改变状态。您拼错了
constructor,并且this.state.clr周围没有大括号。您没有使用从父级传递的道具,并且componentWillMount运行一次......因此在第一次渲染后不会发生任何变化 -
嗨,正如我所说,请忽略语法错误。这是代码的精简版本,而不是真正的代码本身。我还给出了真实代码的链接
-
提供minimal reproducible example 是您的工作。没有人会为您梳理您的代码。自己找出问题并提供一个没有语法错误的完整示例。
-
你没有使用父组件传递的props
-
我正在使用 prop 进行一些计算。变量 C 的值将取决于 props 的值。但不直接使用道具
标签: javascript reactjs react-native components