在不使用状态的情况下,以编程方式更改ReactNative <Text> 组件的文本。

问题描述 投票:0回答:1

你好,StackOverflow成员。

我有一个父级的反应式组件 <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"

但上面的方法行不通... 我试过克隆元素和其他方法... 我所需要的是在不使用回调的状态的情况下,在组件内部快速地改变文本。

有什么建议吗? 这样做是允许的吗? 有什么其他方法可以实现同样的效果吗?

TIA!

reactjs react-native
1个回答
0
投票

而不是 案文 组件使用

<TextInput editable={false} defaultValue={"HELLO PEOPLE"} ref={(ref)=> this.textInputRef=ref} />

然后你就可以像这样直接操作TextInput了。

if(this.textInputRef){
   this.textInputRef.setNativeProps({text:"Change Text Here"})
}

注意: 你不能直接操纵一个 <Text> 因为它使用的是NSTextStorage而不是NSString属性。如果有办法将字符串值转换为NSTextStorage值,那么我们也可以操作Text字段,但据我所知,我们不能。

© www.soinside.com 2019 - 2024. All rights reserved.