如何从值设置“引用”

How to set 'ref' from value?

本文关键字:引用 设置      更新时间:2023-09-26

我正在尝试从值中设置文本输入'ref'。例:

var testtest = 'testvalue'
<TextInput
ref=testtest
autoCapitalize="none"
autoCorrect={false}
autoFocus={false}
placeholderTextColor="#b8b8b8"
color="#b8b8b8"
multiline={true}
onFocus={(() => this.onFieldFocus(testtest))}
style={styles.textInput}
/>

但它不起作用。

我相信你想要这样的东西:

const testtest = 'testvalue'
class TestComponent extends React.Component {
  constructor(props, ctx) {
    super(props, ctx);
    this.onFieldFocus = this.onFieldFocus.bind(this);
  }
  onFieldFocus() {
    const textInput = this.refs[testtest];
  }
  render() {
    return <TextInput ref={testtest} onFocus={this.onFieldFocus} />;
  }
}

来自变量的每个参数都必须在括号内。

因此,您应该有ref={testtest}

然后,您将通过this.refs[testtest]访问它

但是我很好奇什么用例需要动态引用。