根据父状态更新子组件

时间:2017-10-03 14:40:20

标签: reactjs react-native

我是新手做出反应,我遇到了一个我非常肯定是普通解决方案的常见问题,但是,因为我对React的想法不熟悉,我不知道如何解决它。

以下面的例子为例,每当调用TouchableWithoutFeedback回调时,如何让我的孩子重新渲染? (不要告诉我使用不同的组件,这个想法可以应用于许多父子关系 - 当父母发生某些事情时,重新渲染孩子)。

<TouchableWithoutFeedback
    onPressIn={() => { /* what do I do here */ }}
    onPressOut={() => { /* what do I do here */ }}
>
    <View
        style={{
            backgroundColor: /* if touchable is highlighted black, otherwise white */
        }}
    >
        <Text
            style={{
                color: /* if selected, then white, otherwise, black */
            }}
        >
            Some Text
        </Text>
    </View>
</TouchableWithoutFeedback>

编写自定义组件似乎有点冗长(所以每次我需要这种功能时都可以调用setState(),我真的需要吗?)

3 个答案:

答案 0 :(得分:0)

作为一个粗略的例子,您将更新这些回调的状态,并将其作为prop传递给render方法中的子组件。

例如:

this.state = { isHighlighted: false }; // inside the parent component constructor

render() {
  const { isHighlighted } = this.state;

  return (
    <div>
      <FirstChild style={{ backgroundColor: isHighlighted ? 'black' : 'white' }}> 
        <SecondChild style={{ color: isHighlighted ? 'white' : 'black' }}>Some text</SecondChild>
      </FirstChild>
    </div>
  );
}

回调将是:

onPressIn={() => { this.setState({ isHighlighted: true }) }}
onPressOut={() => { this.setState({ isHighlighted: false }) }}

如果您希望通过嵌套组件获得样式,则必须:

a)继续将它们作为道具传递

b)在商店(https://github.com/reactjs/redux

中保持您的州

答案 1 :(得分:0)

您的onPressIn()onPressOut()方法应该更新组件的状态。更改组件的状态时,将调用render()方法并重新呈现组件。如果组件的子属性由于状态更新而发生了更改,那么它们也将被重新呈现。

在您的具体情况下,您应该执行以下操作:

  1. 向组件添加状态。在组件定义的某处添加state = { pressed: false }
  2. 使用onPress方法更新状态,并在设置组件子项的属性时使用状态:
  3. <TouchableWithoutFeedback
        onPressIn={() => { this.setState({pressed: true}) }}
        onPressOut={() => { this.setState({pressed: false}) }}
    >
        <View
            style={{
                backgroundColor: (this.state.pressed) ? 'black' : 'white'
            }}
        >
            <Text
                style={{
                    color: (this.state.pressed) ? 'white' : 'black'
                }}
            >
                Some Text
            </Text>
        </View>
    </TouchableWithoutFeedback>
    

    以上内容在Android设备上的React Native 0.48中进行了测试。

答案 2 :(得分:0)

在你的构造函数中:

this.state={pressedIn:false,onPressOut:false}

然后

<TouchableWithoutFeedback
    onPressIn={() => { this.setState({pressedIn:true,pressedOut:false}}
    onPressOut={() => { {this.setState({pressedOut:true,pressedIn:false}}
>
    <View
        style={{
            backgroundColor: this.state.pressedIn? "someColor":"SomeOtherColor"
        }}
    >
        <Text
            style={{
                color: this.state.onPressOut? "someColor":"SomeOtherColor"
            }}
        >
            Some Text
        </Text>
    </View>
</TouchableWithoutFeedback>
相关问题