reactjs - 如何从函数中调用组件
问题描述
我正在学习 React Native,但在使用TouchableOpacity
.
我在 App.js 组件中有 productHandler() 方法。我想onPress
(当您单击阅读更多时)调用产品组件并将其显示在屏幕上,但不起作用。
当我单击阅读更多时,没有任何反应。
class App extends Component {
productHandler = () => {
return <Product />;
};
render() {
return (
<View style={style.header}>
<View style={style.touchableButtonContainer}>
<TouchableOpacity
style={style.touchableButton}
onPress={this.productHandler}
>
<Text style={style.fontText}>Read More</Text>
</TouchableOpacity>
</View>
<Text>This is just a text</Text>
</View>
);
}
}
这就是 Product.js
class Product extends Component {
render() {
return (
<View>
<Text>Product page</Text>
<Text>Product page</Text>
<Text>Product page</Text>
<Text>Product page</Text>
<Text>Product page</Text>
<Text>Product page</Text>
</View>
);
}
}
我在沙盒中学习,所以这里有这个小代码。
解决方案
问题是您没有告诉 react 在哪里呈现该组件。更好的方法是根据条件处理状态和渲染:
class App extends Component {
state = {
isActive: false
};
productHandler = () => {
this.setState({ isActive: !this.state.isActive });
};
render() {
return (
<View style={style.header}>
<View style={style.touchableButtonContainer}>
<TouchableOpacity
style={style.touchableButton}
onPress={this.productHandler}
>
<Text style={style.fontText}>
{this.state.isActive ? "Hide" : "Read More"}
</Text>
</TouchableOpacity>
</View>
{this.state.isActive && <Product />}
{!this.state.isActive && <Text>This is just a text</Text>}
</View>
);
}
}
推荐阅读
- c - sprintf 在带中断的 32 位 MCU 中重新进入 64 位操作
- php - (PHP) 如何检测用户的计算机/浏览器处于暗模式?
- javascript - Angular:将方法作为参数传递
- javascript - 不正确的 Javascript 对象语法
- unity3d - Unity 独立应用程序:分辨率缩放问题 (OSX)
- websocket - 如何将自定义标头从 NGINX 反向代理传递到服务器中的 SockJs websocket 连接?
- c# - 如何在运行时使用 EF 和 Structuremap 更改连接字符串?
- android - 应用内键盘:不同设备上的不同行为
- html - “查看源代码”无法编辑的表单元素
- c# - 选择每个 IGrouping 中的第一个,聚合一些属性而不显式分配每个非聚合属性