reactjs - 更改 ReactNative 的文本以编程方式组件而不使用状态
问题描述
您好 StackOverflow 成员,
我有一个父 react-native 组件<Cell/>
,里面有一个子<Text/>
组件。子组件必须是一个<Text/>
组件,我不能将其更改为另一个组件。请参见下面的示例...
let renderedCell = (<Cell>
<Text>HELLO PEOPLE</Text>
</Cell>)
我想以编程方式将“HELLO PEOPLE”更改为“Hello World”,而不通过回调使用状态。我已经“检查”了子组件,我使用console.log(renderedCell.props.children)
...
{
$$typeof: Symbol(react.element)
type:
$$typeof: Symbol(react.forward_ref)
render: ƒ Text(props, forwardedRef)
displayName: "Text"
propTypes: {ellipsizeMode: ƒ, numberOfLines: ƒ, textBreakStrategy: ƒ, …}
__proto__: Object
key: null
ref: null
props:
style: (3) [(...), (...), (...)]
children: "HELLO PEOPLE"
__proto__: Object
_owner: FiberNode {tag: 1, key: null, stateNode: Table, elementType: ƒ, …}
_store: {validated: true}
_self: null
_source: {fileName: "component.js", lineNumber: 146, columnNumber: 17}
__proto__: Object
}
我尝试过以编程方式将文本从“HELLO PEOPLE”更改为“Hello World”,如下所示:
renderedCell.props.children.props.children = "Hello World"
但上述方法不起作用......我已经尝试克隆元素和其他东西......我所需要的只是以编程方式即时更改组件内的文本,而不使用回调中的状态。
有什么建议么?这是允许的吗?还有其他方法可以做到这一点并完成同样的事情吗?
蒂亚!
解决方案
代替Text组件使用
<TextInput editable={false} defaultValue={"HELLO PEOPLE"} ref={(ref)=> this.textInputRef=ref} />
那么您可以像这样直接操作 TextInput
if(this.textInputRef){
this.textInputRef.setNativeProps({text:"Change Text Here"})
}
注意:您不能直接操作 a<Text>
因为它使用 NSTextStorage 而不是 NSString 属性。如果有办法将字符串值转换为 NSTextStorage 值,那么我们也可以操作 Text 字段,但据我所知,我们不能。
推荐阅读
- python - SUMO 和 TraCI,多个客户端 - 一个连接
- javascript - Vue js在编译时正在删除脚本标签
- powershell - 对包含给定短语的字符串应用过滤器并返回之后发生的所有内容
- javascript - 根据另一个单词数组对一组单词进行排序
- c# - CodeDOM:命名参数
- node.js - node.js @sendgrid/mail 错误:未经授权
- kubernetes - kube-apiserver healthz 调用中检查了什么?
- css - 当我知道值不是空白时,Asp.net 参数显示为空
- eclipse-emf - 如何在同一工作空间中而不是在运行时 Eclipse 环境中从 Ecore 元模型实例化模型?
- jquery - 单击链接时删除超链接