javascript - 是否可以随时从另一个组件渲染任何组件?
问题描述
我有一个关于 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 中是否可行,我该怎么做?
解决方案
根据您的评论,您需要隐藏第一个组件,因为按钮单击第一个组件。如果是这种情况,您可以按以下方式进行。
- 首先,在父组件中添加一个状态变量,指示是否渲染第一个组件。
- 然后向父组件添加一个函数来更新此字段并将其作为 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>
);
}
}
推荐阅读
- android - 以图形方式显示附近扫描的蓝牙设备,如下所示
- reactjs - 为什么在 HTML 中直接使用 React(而不是在反应环境中)是一个坏主意?
- html - 给具有对角线边缘的元素一个边框?
- c# - 找到最接近前5000米的记录
- db2 - 返回单个 CASE DB2 上的多个列
- enums - 为什么我们使用 Option 枚举?
- c++ - 如何在 Qt c++ 中使用 Secure WebSocket 连接服务器
- context-free-grammar - 为什么这个 DK 测试是错误的?
- java - 计算数组中不同元素数量的递归方法
- android - 需要对片段使用 BottomSheetBehavior 和 ScrollingViewBehavior