好的。让我们把问题变得非常简单。
我有一个名为 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"/>
它有效。
现在,我有一个返回 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/