代码之家  ›  专栏  ›  技术社区  ›  Mahdi Bashirpour

React native:动态调用方法

  •  1
  • Mahdi Bashirpour  · 技术社区  · 6 年前

    我在用 React Native ref 在里面 TextInput 我需要那个方法。

    renderInput(id) {
        <TextInput
            ref={(input) => this.myInput = input}
        />
    }
    

    this.myInput .

    我试过了,结果弄错了: this.myInput[id] this[id].myInput

    2 回复  |  直到 6 年前
        1
  •  1
  •   Mohammed Ashfaq    6 年前
    constructor(props) {
      super(props);
      this.inputs = {};
    }
    
    
    //  params Object should be in this format   {id:324, referenceKey: 'one'};
    
    renderTextInput(params) {
      return <TextInput ref={input => { this.inputs[params.referenceKey] = input }}/>
    } 
    

    componentDidMount(){
      this.inputs['one'].focus()
    }
    
        2
  •  2
  •   Bhojendra Rauniyar    6 年前

    你应该使用 current :

    this.myInput.current[id]
    

    方法如下:

    // First, create a reference (in the constructor)
    this.myInput = React.createRef()
    // Then, assign the ref (in the element)
     <TextInput ref={this.myInput} />
    // Now, to access the reference
    // this.myInput.current.<<property you wanted to access>>
    this.myInput.current[id] // id is defined as a variable
    // this will get the dom id
    // this.myInput.current.id
    

    但是如果你坚持使用回调ref,就像你现在使用的一样,那么你可以传递id属性:(另外,我认为你要寻找的答案是)

    renderInput(id) {
        <TextInput
            ref={(input) => this.myInput = input}
            id={id} {/* you were missing this in fact */}
        />
    }
    

    this.myInput.id // will work fine, coz we have id prop now
    // gets DOM id that you assigned in your element