reactjs - 如何设置/重置属性以在运行时 react 元素

标签 reactjs react-native

好的。让我们把问题变得非常简单。

我有一个名为 ColorText 的组件。

class ColorText extends React.Component{
  render(){
    return (<Text style={{color:this.props.color}}>{this.props.text}</Text>);
  }
}

当我打电话时

<ColorText color="red" text="I am red text"/>

它有效。

enter image description here

现在,我有一个返回 ColorText 的函数,如下所示

 getGreenText = () => {
    return (<ColorText text="Default text" color="green"/>);
 }

我想像这样在运行时重置文本属性

const GreenText = this.getGreenText();
GreenText.props.text = "I am green text";

这不起作用。并打印默认文本

所以,这是我的问题。 是否可以在运行时设置/重置 react 组件的属性?正确的做法是什么?

注意:我用谷歌搜索了很多,找不到任何积极的东西。如果您对这个问题有任何疑问,请在评论中问我。完整源代码可从here获取

编辑:

我知道这可以通过简单地将变量传递给这样的方法来完成

getGreenText = (text) => {
    return (<ColorText text={text || "Default text"} color="green"/>);
}

但这不是我想要完成的事情。我想通过从方法返回的对象来设置它。是否可以 ?

最佳答案

你不能。这是设计使然。如果你尝试这样做

GreenText.props.text = "I am green text";

它会抛出错误,因为 props 是不可变的。

你能给出一个需要做类似事情的用例吗?永远不需要它。


可能的解决方案

您可以简单地将文本作为参数传递,如下所示:

getGreenText = (text) => {
    return (<ColorText text={text || "Default text"} color="green"/>);
}

render() {
    const GreenText = this.getGreenText("I am green text");
    return (
        <View style={styles.container}>
            <ColorText color="red" text="I am red text"/>
            {GreenText}
        </View>
    );
}

如果您需要推迟文本的更新,只需使用状态即可。

否则,您可以使用 ref 实现您想要的目标(请参阅: https://reactjs.org/docs/refs-and-the-dom.html )。

关于reactjs - 如何设置/重置属性以在运行时 react 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50967819/

相关文章:

reactjs - 为什么我的 NavLink 没有使用 Semantic-ui-react 设置为事件状态?

react-native - React-native上的加载图像错误:意外字符

android - "SDK directory does not exist"错误

javascript - 无法在事件处理程序中访问 React 实例(this)

javascript - 使用 onClick 时进行 React 渲染

javascript - React-native 博览会中 ImageBackground 上方的 LinearGradient

javascript - 获取货币符号的特殊文本字符的 HTML 实体代码

javascript - 如何测试商店单例?

javascript - 变量不会同时从 React setState 改变

javascript - 使用 useState() 共享组件状态以实现导航中的事件链接