Reactjs 如何在React Native Button组件中更改标题属性
我有几个React组件在应用程序中看起来像这样:Reactjs 如何在React Native Button组件中更改标题属性,reactjs,react-native,button,Reactjs,React Native,Button,我有几个React组件在应用程序中看起来像这样: <View style={{margin: 5}}> <Button title='Enable Headlights' color='#00759A' onClick={doChanges}/> </View> 我希望按钮组件在单击时更改其颜色和文本。我本来打算让函数doChanges来做这件事,但是我想不出一个方法来修改标题和颜色属性。我见过定制的组件,它们通过在组件中调用setS
<View style={{margin: 5}}>
<Button title='Enable Headlights' color='#00759A' onClick={doChanges}/>
</View>
我希望按钮组件在单击时更改其颜色和文本。我本来打算让函数doChanges来做这件事,但是我想不出一个方法来修改标题和颜色属性。我见过定制的组件,它们通过在组件中调用setState来改变状态,但Button不是我制作的组件。我试着做了以下几点:
var text = "Enable headlights"
function doChanges(text) {
text = "Disable headlights"
}
<View style={{margin: 5}}>
<Button title={text} color='#00759A' onClick={()=> {doChanges(text)}}/>
</View>
var text=“启用前照灯”
函数更改(文本){
text=“禁用前照灯”
}
{doChanges(text)}}/>
但这似乎不是我想要的方式。我认为这是因为即使变量文本在变化,实际的组件也不会重新排序,所以文本中的变化永远不会出现
似乎没有办法强制组件重新渲染,我也不知道如何修改按钮组件的标题和颜色属性
为了获得我想要的功能,我是否必须创建一个自定义组件,它是从Button子类化的?或者有没有一个具体的方法来让我在React中做类似的事情
任何帮助都将不胜感激 如果要在UI级别进行更改,则应使用状态来呈现更新的视图 比如: 如果使用类组件:
class Demo extends Component {
constructor(props) {
super(props)
this.state = {
buttonText: "Enable headlights"
}
this.doChanges = this.doChanges.bind(this);
}
function doChanges(text) {
this.setState({ buttonText: "Disable headlights" });
}
render() {
return (
<View style={{margin: 5}}>
<Button title={this.state.} color='#00759A' onClick={()=> {doChanges(text)}}/>
</View>
)
}
}
const Demo = props => {
const [buttonText, setButtonText] = useState("Enable headlights")
function doChanges(text) {
setButtonText("Disable headlights");
}
return (
<View style={{margin: 5}}>
<Button title={text} color='#00759A' onClick={()=> {doChanges(text)}}/>
</View>
)
}
类演示扩展组件{
建造师(道具){
超级(道具)
此.state={
按钮文字:“启用前照灯”
}
this.doChanges=this.doChanges.bind(this);
}
函数更改(文本){
此.setState({buttonText:“禁用前照灯”});
}
render(){
返回(
{doChanges(text)}}/>
)
}
}
如果您正在使用功能组件:
class Demo extends Component {
constructor(props) {
super(props)
this.state = {
buttonText: "Enable headlights"
}
this.doChanges = this.doChanges.bind(this);
}
function doChanges(text) {
this.setState({ buttonText: "Disable headlights" });
}
render() {
return (
<View style={{margin: 5}}>
<Button title={this.state.} color='#00759A' onClick={()=> {doChanges(text)}}/>
</View>
)
}
}
const Demo = props => {
const [buttonText, setButtonText] = useState("Enable headlights")
function doChanges(text) {
setButtonText("Disable headlights");
}
return (
<View style={{margin: 5}}>
<Button title={text} color='#00759A' onClick={()=> {doChanges(text)}}/>
</View>
)
}
const Demo=props=>{
常量[buttonText,setButtonText]=useState(“启用前照灯”)
函数更改(文本){
setButtonText(“禁用前照灯”);
}
返回(
{doChanges(text)}}/>
)
}
查看有关该州的更多信息:
您可以使用
useState
hook更新某些道具,并使用新道具重新渲染组件