【问题标题】:How to set 'ref' from value?如何从值设置'ref'?
【发布时间】:2016-03-16 12:16:04
【问题描述】:

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

但它不起作用。

【问题讨论】:

    标签: javascript reactjs react-native mobile-development


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      然后你可以通过this.refs[testtest]访问它

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

      【讨论】:

      • onfocus 怎么样?我需要写 onFocus={(() => this.onFieldFocus({testtest}))} ?
      • onFocus = {this.onFieldFocus.bind(this, testtest)} 对我来说似乎更干净
      • 我认为该评论是关于在testtest 周围添加第二组卷曲。答案是否定的,一旦你已经在一对卷发中,你就不必再添加第二组卷发了。把它想象成使用 curlies 回到 javascript 世界。如果您要再次将 JSX 放入 curlies 中,那么您需要第二组,但在这种情况下,一个就足够了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2017-11-21
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      相关资源
      最近更新 更多