如何从值设置 'ref'?

How to set 'ref' from value?

我正在尝试根据值设置 TextInput '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}
/>

但是不行。

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

因此你应该 ref={testtest}

然后您可以通过 this.refs[testtest]

访问它

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

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

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} />;
  }
}