LoginSignup
3
1

More than 5 years have passed since last update.

[react]子要素に複数配置したinputのvalueを取得する

Posted at

下記のようなコンポーネント構成のinput valueを親コンポーネントでこんな風に取得できた。

sample.jsx
class Parent extends React.Component {
 constructor(props) {
  super(props);
  this.inputRefs = []; 
 }

 // ボタン押下処理で子要素のinput valueを全部取得したい
 clickEvent() {
   this.props.datas.forEach(function(data,index){
     this.inputRefs[index].inputA.value,
     this.inputRefs[index].inputB.value,
     this.inputRefs[index].inputC.value
   },this);    
 }

 render() {
    var childInputGroup = this.props.datas.map(function(data, index){
            return <ChildInput key={...} ref={(input) => {this.inputRefs[index] = (input)}}/>
        },this);

    return (
      <div>
        {childInputGroup}
      </div>
    );
  }

}

class ChildInput extends React.Component {

  render() {
    return(
      <div>        
        <input ref={(input) => {this.inputA = input}} />
        <input ref={(input) => {this.inputB = input}}/>
        <input ref={(input) => {this.inputC = input}}/>
      </div>
    );
  }

}

親コンポーネントのthis.inputRefsに、生成した子要素分の参照を入れておく。
子要素のinputにもそれぞれrefを付与しておくと、上記の形でinput valueが取れる。

map()の第2引数にthisを渡さないと、this.inputRefがundefinedになるので注意。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1