React native 如何为react native中已存在的状态添加值?
我有一个名为React native 如何为react native中已存在的状态添加值?,react-native,React Native,我有一个名为projectname this.state={ projectname: "" } 我需要在单击按钮时更改状态值(例如,从“Project”更改为“Project-01”) 此处状态projectname会动态更改。我想知道如何用项目名称添加-01,我不确定我是否正确理解了你的观点,但我想你正在寻找类似的东西 构造函数(道具){ 超级(道具); 此.state={ 项目名称:“项目名称” }; this.updateState=this.aba.bind(this) } 不
projectname
this.state={
projectname: ""
}
我需要在单击按钮时更改状态值(例如,从“Project”更改为“Project-01”)
此处状态
projectname
会动态更改。我想知道如何用项目名称添加-01,我不确定我是否正确理解了你的观点,但我想你正在寻找类似的东西
构造函数(道具){
超级(道具);
此.state={
项目名称:“项目名称”
};
this.updateState=this.aba.bind(this)
}
不动产(){
这是我的国家({
projectname:this.state.projectname.concat(“-01”)
})
}
我不确定我是否正确理解了你的观点,但我认为你在寻找类似的东西
构造函数(道具){
超级(道具);
此.state={
项目名称:“项目名称”
};
this.updateState=this.aba.bind(this)
}
不动产(){
这是我的国家({
projectname:this.state.projectname.concat(“-01”)
})
}
您可以使用setState
方法更改如下状态:
this.setState({
projectname : "new Project name"
})
您可以使用
setState
方法更改如下状态:
this.setState({
projectname : "new Project name"
})
您需要使用
this.setState()
来更改组件的状态
使用按钮
组件的onPress
处理程序执行此操作的常用方法:
- 创建一个使用
this.setState
- 在类构造函数中绑定这样的方法
- 将该方法传递到
按钮的
proponPress
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>
);
}
}
但您必须小心,因为多次单击将添加多次“-01”(例如,4次单击将导致“Project-01-01-01-01”)。您需要使用
this.setState()
更改组件的状态
使用按钮
组件的onPress
处理程序执行此操作的常用方法:
- 创建一个使用
this.setState
- 在类构造函数中绑定这样的方法
- 将该方法传递到
按钮的
proponPress
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>
);
}
}
但您必须小心,因为多次单击将添加多次“-01”(例如,4次单击将导致“Project-01-01-01”)