问题
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