how to change text of button in listview in react

2019-05-10 05:09发布

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>

      />
    );
  }

3条回答
虎瘦雄心在
2楼-- · 2019-05-10 05:30
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 />}

查看更多
疯言疯语
3楼-- · 2019-05-10 05:45

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

查看更多
Lonely孤独者°
4楼-- · 2019-05-10 05:48

Bind ConPressed() to scope.

constructor(props) {
    super(props);
    this.state = {
        button_text:"Connect",
    }
    this.ConPressed = this.Conpressed.bind(this);
}
查看更多
登录 后发表回答