我有一个组件,里面包含Switch组件。整个组件都可以点击。当您点击此组件时,它会触发dispatch(修改redux存储),并导致重新渲染此组件。
我需要的是不重新渲染整个组件,而只是将Switch组件动画到正确的状态。
类似于这样:
<TouchableOpacity onPress={onPress}>
<Text>{this.props.title}</Text>
<Switch value={this.state.active}/>
</TouchableOpacity>
有什么想法吗?
我发现这是一个很常见的用例,我知道我将遇到许多类似的情况,所以我需要这种行为,但我在网络上找不到任何示例或解决方案。也许我只是漏了什么。
谢谢
--- 编辑 ---
我也尝试过这个。 我尝试使用shouldComponentUpdate禁用更新,我尝试仅在willRecieveProps和/或toggle中设置状态,甚至没有toggle。 我还尝试了LayoutAnimation的玩法。 但是都无济于事,this.setState()只是不能动画切换组件。 我还尝试玩弄this._switch._rctSwitch.setNativeProps({ value:nextProps.active }),但这也行不通(而且_rctSwitch的问题很大)。
class ViewWithSwitchInside extends React.Component {
constructor(props) {
super(props)
this.toggle = this.toggle.bind(this);
this.state = {
active: props.active
}
}
componentWillReceiveProps(nextProps) {
if (this.state.active != nextProps.active) {
this.setState({ active: nextProps.active })
}
}
toggle() {
let newValue = !this.state.active
this.setState({
active: newValue,
})
if (typeof this.props.onClick === 'function') {
this.props.onClick(newValue)
}
}
render() {
return (
<TouchableWithoutFeedback onPress={this.toggle}>
<View>
<Text>{this.props.title}</Text>
<Switch value={this.state.active} />
</View>
</TouchableWithoutFeedback>
)
}
}
setState
来改变它时,它会立即跳到另一个位置,没有平滑的动画效果。这与你的问题不同吗? - hippietrail