【问题标题】:React Native: Rendering Component on Button ClickReact Native:在按钮单击时呈现组件
【发布时间】:2017-06-22 17:33:03
【问题描述】:

我有一个组件列表,当用户单击按钮时要呈现这些组件。该屏幕应该是一个搜索屏幕,用户在其中输入查询,当他们点击搜索按钮时,会显示结果列表。但是,当我尝试使用 onPress 渲染组件时,什么也没有发生。对于这个例子,我只是打印文本而不是使用 map 来打印组件。

renderResults() {  
   return <Text> Doesn't get printed </Text>
  }

  render() {
    return (
      <View>
        <Button
          onPress={ this.renderResults.bind(this) } //use .bind(this) to access state in renderResults
          title="Search!"
          color="#841584" />
       </View>
      );
  }

【问题讨论】:

  • 您必须在 renderResults 方法中更改组件(或应用程序)的状态。现在 renderResult 方法不会触发状态更新。如果你想改变组件的状态,你必须调用 setState。

标签: javascript react-native react-native-ios


【解决方案1】:
export default class App extends Component {
    state={
      isVisible:false
    }

    renderResults=() =>{ 
      this.setState({
        isVisible:!this.state.isVisible//toggles the visibilty of the text
      })
    } 

    render() { 
      return (
        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
          {this.state.isVisible?<Text> get printed </Text>:null}
          <Button onPress={ this.renderResults} 
            title="Search!" 
            color="#841584" /> 
      </View> 
      );
     }
}

试试这个代码。

您可以在link 上运行演示

【讨论】:

  • 我不明白这个拒绝投票的答案有什么问题。
【解决方案2】:

React 不知道它需要用这个方法重新渲染视图。相反,通过更新本地状态强制重新渲染。我会在构造函数中执行state = {buttonPressed: false} 之类的操作,然后在onPress 中执行this.setState({ buttonPressed: true}。然后只需在渲染中使用一个简单的布尔值即可返回文本或按钮,具体取决于状态中的buttonPressed 是真还是假

【讨论】:

    【解决方案3】:

    简单例如。由@Max Millington 回答。您可以使用Conditional rendering 来检查状态是真还是假。

    constructor () {
       super();
       this.state = {printText:false};
    } 
    
    showText = () => {
       this.setState({printText:true});
    }
    
    render() {
      return (
       <View>
        <Button
          onPress={() => this.showText() } 
          title="Search!"
          color="#841584" />
         {this.state.printText && <Text> Printed text... </Text> }
       </View>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-28
      • 2020-09-14
      • 2018-05-29
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2021-02-08
      相关资源
      最近更新 更多