how to change text of button in listview in react native?

岁酱吖の 提交于 2020-01-13 13:53:47

问题


I am trying to change text of button which is in listview quickly after click on it?

I am trying with following code to implement this but i cant do it i.e its not working. How can i do it? please help.

constructor(props) {
    super(props);
    this.state = {
      button_text:"Connect",
    }
  }

  ConPressed() {
    this.setState({
      button_text: "Connected",
    });
  }

  render() {
    return (
      <ListView
        dataSource={this.state.sa}
        renderRow={(rowData) => 

       <TouchableHighlight onPress={() => this.ConPressed()}>
          <Text>{this.state.button_text}</Text>
       </TouchableHighlight>

      />
    );
  }

回答1:


export default class ListItem extends Component {
  constructor(props) {
    super(props);

    this.state = {
      button_text: 'Connect',
    }
  }


  ConPressed = () => {
    this.setState({ button_text: 'Connected' });
  }


  render() {
    return (
      <TouchableHighlight onPress={this.ConPressed}>
        <Text>{this.state.button_text}</Text>
      </TouchableHighlight>
    );
  }
}

So now you want to import your ListItem in your original file, and use that in your renderRow.

renderRow={() => <ListItem />}




回答2:


In your code for the touchable you are passing a method execution and not a method reference.

<TouchableHighlight
onPress={() => this.ConPressed()}>
<Text>{this.state.button_text}</Text>
</TouchableHighlight>

Which means conPressed will get executed as soon as the component gets mounted which is probably why you are getting the error. Try changing it to

<TouchableHighlight
onPress={() => this.ConPressed}>
<Text>{this.state.button_text}</Text>
</TouchableHighlight>

And also

this.ConPressed = this.ConPressed.bind(this)

In your constructor




回答3:


Bind ConPressed() to scope.

constructor(props) {
    super(props);
    this.state = {
        button_text:"Connect",
    }
    this.ConPressed = this.Conpressed.bind(this);
}


来源:https://stackoverflow.com/questions/48326655/how-to-change-text-of-button-in-listview-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!