首页 > 解决方案 > 更改 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"

但上述方法不起作用......我已经尝试克隆元素和其他东西......我所需要的只是以编程方式即时更改组件内的文本,而不使用回调中的状态。

有什么建议么?这是允许的吗?还有其他方法可以做到这一点并完成同样的事情吗?

蒂亚!

标签: reactjsreact-native

解决方案


代替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 字段,但据我所知,我们不能。


推荐阅读