使用道具获取反应状态名称

时间:2018-10-19 17:27:55

标签: reactjs

我想知道是否可以使用this.props获得州名。 示例:

this.state.(this.props.name)

我正在这样设置状态:

  onInputChange = (e) => {
   this.setState({[e.target.name]: [value: e.target.value, error: this.props.error]})
  }

e.target.name来自<input name={this.props.name} />

我需要某种方式来显示数组中的状态。

下面的完整代码。在确定此步骤之后,我将在此处添加输入验证。

import React, {Component} from 'react';

class Input extends React.Component {
 constructor(props){
  super(props);
  this.state = {

  }
 }
 onInputChange = (e) => {
  this.setState({[e.target.name]: [value: e.target.value, error: this.props.error]})
 }
 render () {
  return(
   <div className="form-group">
    <span>HERE WILL GO ERROR FROM STATE ARRAY AFTER VALIDATION</span>
    <input
     onChange={this.onInputChange}
     type={this.props.type}
     name={this.props.name}
     className="form-control input-lg"
     placeholder={this.props.placeholder}
    />
  </div>
  )
 }
}

export default Input;

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用this.state [this.props.name]。

我已经在沙箱中创建了工作代码。请看看https://codesandbox.io/s/pp3o0r2zrq