Reputation: 85
I have a state property called projectname
this.state={
projectname: ""
}
I need to change the state value (for example from "Project" to "Project-01" ) when a button is clicked.
Here state projectname
changes dynamically. I want to know to how to add -01 with project name
Upvotes: 0
Views: 1697
Reputation: 2078
You need to use this.setState()
to change your component's state.
The common way to do this by using the onPress
handler of the Button
component:
this.setState
onPress
prop of a Button
Here is an example
import React from "react";
import { View, Button } from "react-native";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
projectname: "Project", // Inital value in your example
};
// Binding the method that will handle the click.
this.onClickHandler = this.onClickHandler.bind(this);
}
// The actual method that will alter the state.
onClickHandler() {
this.setState({
projectname: "Project-01",
});
}
render() {
return() (
<View>
{/* A button with the method passed to onPress. */}
<Button title="Click me" onPress={this.onClickHandler} />
</View>
);
}
}
Now, if you explicitly want to add "-01" to the projectname
value, you need to reference the current value of projectname
when altering the state:
onClickHandler() {
this.setState({
projectname: this.state.projectname + "-01"
});
}
But you have to be careful because multiple clicks will add multiple times "-01" (for example, 4 clicks will result in "Project-01-01-01-01").
Upvotes: 1
Reputation: 1735
You can use setState
method to change the state like this :
this.setState({
projectname : "new Project name"
})
Upvotes: 0
Reputation: 1932
I'm not sure I got your point correctly or not but I think you are looking for something like this
constructor(props) {
super(props);
this.state = {
projectname:"projectname"
};
this.updateState= this.aba.bind(this)
}
updateState () {
this.setState({
projectname : this.state.projectname.concat("-01")
})
}
Upvotes: 1