【发布时间】:2017-10-01 22:21:22
【问题描述】:
我正在创建一个自定义导航器组件。我需要为 Navigator 的堆栈组件提供一个 navigator 道具,以允许它们像这样推送和弹出场景:
this.props.navigator.push(<Product id='4815'>)
this.props.navigator.pop()
为了实现这个结果,在我的 Navigator 类中,我使用了React.cloneElement():
class Navigator extends Component {
constructor(props) {
super(props)
this.state = { stack: [this._addNavigator(props.children)] }
}
_addNavigator(scene) {
return React.cloneElement(scene, {
navigator: {
push: this.push,
pop: this.pop,
popToRoot: this.popToRoot
}
})
}
push(scene) {
this.setState({
stack: [...this.state.stack, this._addNavigator(scene)]
})
}
...
}
一切都很好,除了特定场景。
class App extends Component {
constructor(props) {
super(props)
this.state = { toggle: false }
}
render() {
return (
<View>
<TouchableOpacity onPress={() => {
this.setState({ toggle: !this.state.toggle })
}}>
<Text>Toggle</Text>
</TouchableOpacity>
<Navigator>
<SampleScene backgroundColor={this.state.toggle ? 'green' : 'black'} />
</Navigator>
</View>
)
}
当我将一些可变属性传递给 Navigator 子组件时,只要该属性发生更改,子组件就不会重新渲染。在上面的示例中,SampleScene 的背景颜色保持黑色(因为 toggle 的 App 类初始状态设置为 false),尽管用户按下了切换按钮。似乎 SampleScene 的 render() 方法只被调用了一次。如何解决此问题?
【问题讨论】:
标签: javascript reactjs react-native