首页 > 解决方案 > 如何从函数中调用组件

问题描述

我正在学习 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>
    );
  }
}

我在沙盒中学习,所以这里有这个小代码。

标签: reactjsreact-native

解决方案


问题是您没有告诉 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>
    );
  }
}

这是现场演示:https ://codesandbox.io/s/react-native-oln9t


推荐阅读