使用按钮更改文本颜色

dke*_*haw 6 reactjs react-native react-native-ios

我正在尝试创建一个简单的 React Native 应用程序:

  1. 呈现“你好,[名字]!” 当用户输入姓名时(这部分有效)
  2. 更改“你好,[姓名]!” 按下按钮时的文本颜色。

关于我应该如何去做的任何想法?

我给出this了黑色的初始状态,但这似乎没有任何作用。

我想要发生的是在单击红色按钮时触发 makeRed,这将使文本变为红色。一旦我完成这项工作,我将添加更多颜色按钮。

谢谢!

请参阅下面的我的 App.js 代码。所有其他文件都保持默认状态。

import React, { Component } from 'react';
import {
  AppRegistry,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  View,
  Button
} from 'react-native';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      text: 'World',
      color: 'black'
    };
  }

  makeRed = () => {
    this.setState({
      color: 'red'
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={[styles.welcome, {color: undefined}]}>
          Hello, {this.state.text}!
        </Text>
        <TextInput
          style={styles.instructions}
          placeholder="Enter a name here!"
          onChangeText={(text) => this.setState({text})}
        />
        <Button
          title='?'
          onPress={this.makeRed}
          color='red'
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 40,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
Run Code Online (Sandbox Code Playgroud)

这是应用程序的屏幕截图以供参考: 应用程序屏幕截图

Viv*_*shi 4

您需要做的就是改变这一点:

style={[styles.welcome, {color: undefined}]}
Run Code Online (Sandbox Code Playgroud)

style={[styles.welcome, {color : this.state.color }]}
Run Code Online (Sandbox Code Playgroud)

请检查:工作演示