【问题标题】:Is that possible to render any component from the other at any time?是否可以随时从另一个渲染任何组件?
【发布时间】:2020-03-11 05:35:47
【问题描述】:

我有一个关于 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 中是否可行,我该怎么做?

【问题讨论】:

  • 为什么要触发它?是不可能的。 render 方法由 react-native 系统处理以渲染可视 dom
  • 如果可能的话,我会使用解决方案来解决这个问题; stackoverflow.com/questions/58858370/…
  • 对于这种情况,您可以将其组合在一个组件中。所以你可以控制第二个组件。像react-native-dropdown

标签: javascript reactjs react-native components render


【解决方案1】:

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

  • 首先,在父组件中添加一个状态变量,指示是否渲染第一个组件。
  • 然后向父组件添加一个函数来更新此字段并将其作为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>
    );
  }
}
  • 在第一个组件中,当按钮上触发onClick事件时,调用hideFirst prop方法。
class FirstChild extends Component {
  render() {
    return( 
    <View>
      <Text>{Math.random()}</Text>
      <Button 
        title='Render second child'
        onClick={() => this.props.hideFirst()}
      />
    </View>
    );
  }
}

【讨论】:

  • 当我测试您的解决方案时,第二个组件不会呈现,在我的情况下,父组件可以在启动情况下呈现这两个子组件,而不是在任何按下按钮时只需要呈现第二个组件。 (第一个组件不应通过按下按钮再次呈现)
  • 我根据你上面的详细信息更新了我的答案
猜你喜欢
  • 2013-01-20
  • 2017-12-10
  • 2018-12-12
  • 2012-10-17
  • 2015-11-20
  • 1970-01-01
  • 2019-04-19
  • 1970-01-01
  • 2021-12-04
相关资源
最近更新 更多