首页 > 解决方案 > 是否可以随时从另一个组件渲染任何组件?

问题描述

我有一个关于 react-native 组件可能性的问题,为了解释我的问题,我实现了以下示例代码;

export default class App extends Component {
  render() {
    return(
      <View>
        <FirstChild/>
        <SecondChild/>
      </View>
    );
  }
}

class FirstChild extends Component {
  render() {
    return( 
    <View>
      <Text>{Math.random()}</Text>
      <Button 
        title='Render second child'
      />
    </View>
    );
  }
}

class SecondChild extends Component {
  render() {
    return(
      <View>
        <Text>{Math.random()}</Text>
      </View>
    );
  }
}

如您所见,有 2 个子组件,我只想随时触发第二个组件的渲染功能或从第一个组件渲染第二个组件。

这在 react-native 中是否可行,我该怎么做?

标签: javascriptreactjsreact-nativecomponentsrender

解决方案


根据您的评论,您需要隐藏第一个组件,因为按钮单击第一个组件。如果是这种情况,您可以按以下方式进行。

  • 首先,在父组件中添加一个状态变量,指示是否渲染第一个组件。
  • 然后向父组件添加一个函数来更新此字段并将其作为 a 传递prop给第一个组件。
  • 根据上述状态变量的值有条件地渲染第一个组件。
export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
        showFirst: true
    };
  }

  hideFirst = () => {
    this.setState({
        showFirst: false
    });
  };

  render() {
    return(
      <View>
        {
            (this.state.showFirst) &&
            (<FirstChild hideFirst={this.hideFirst}/>)
        }
        <SecondChild/>
      </View>
    );
  }
}
  • 在第一个组件中,在按钮上触发事件hideFirst时调用 prop 方法。onClick
class FirstChild extends Component {
  render() {
    return( 
    <View>
      <Text>{Math.random()}</Text>
      <Button 
        title='Render second child'
        onClick={() => this.props.hideFirst()}
      />
    </View>
    );
  }
}

推荐阅读