如何获取输入值并将其设置为单击状态,并控制台记录它以进行反应

时间:2020-02-12 03:36:47

标签: javascript reactjs

我试图在单击时获取用户输入,并将其设置为尝试在控制台上显示的状态,但是每次单击按钮时,状态属性都为空。

例如。 This is what I want to see in console log

但是我得到: Empty state properties

这是我的代码



  class WalkInBook extends Component {
    constructor(props)
    {
      super(props);
      this.state={
        firstName:'',
        lastName:'',
        phone:'',
        email:'',
        course:'',

      };
    }

    handleClick = () =>
    {
      console.log(this.state);
    }

    handleChangeText(event){
      const target = event.target;
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]:value
      })
    }




    render() {

      console.log(this.state); 
      //
    // MATERIAL-UI REQUIREMENT #2: Needed for accessing "styles" CB function declared above this class.
    const { classes } = this.props;
      return (
        <div align="center">
           <Typography>
           <div>
             <div className={classes.root} noValidate autoComplete="off">
            <TextField onChangeText={this.handleChangeText} id="standard-basic" name="firstName" label="First Name" />
             </div>
             <div className={classes.root} noValidate autoComplete="off">
               <h1>{this.state.data}</h1>
            <TextField id="standard-basic" name="lastName" label="Last Name" />
             </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField  id="standard-basic" name="phone"  label="Phone" />
            </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField  id="standard-basic" name="email" label="Email" />
            </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField  id="standard-basic" name="course"  label="Course" />
            </div>
           </div>
           <div className={classes.root} noValidate autoComplete="off">
           <Button type="submit" onClick={this.handleClick} variant="outlined">Submit</Button>
           </div>
            </Typography>
        </div>
      );
    }
  } 

2 个答案:

答案 0 :(得分:0)

我已经更新了您的代码。请在下面看看:

class WalkInBook extends Component {
    constructor(props)
    {
      super(props);
      this.state={
        firstName:'',
        lastName:'',
        phone:'',
        email:'',
        course:'',

      };
    }

    handleClick = () => {
      console.log(this.state);
    }

    handleChangeText = (event) => {
      const { target:{ value, name } } = event
      this.setState({ [name]:value });
    }

    render() {
    const { classes } = this.props;
      return (
        <div align="center">
           <Typography>
           <div>
             <div className={classes.root} noValidate autoComplete="off">
            <TextField onChangeText={(e) => this.handleChangeText(e)} id="standard-basic" name="firstName" label="First Name" />
             </div>
             <div className={classes.root} noValidate autoComplete="off">
               <h1>{this.state.data}</h1>
            <TextField onChangeText={(e) => this.handleChangeText(e)} id="standard-basic" name="lastName" label="Last Name" />
             </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField onChangeText={(e) => this.handleChangeText(e)}  id="standard-basic" name="phone"  label="Phone" />
            </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField onChangeText={(e) => this.handleChangeText(e)}  id="standard-basic" name="email" label="Email" />
            </div>
            <div className={classes.root} noValidate autoComplete="off">
            <TextField onChangeText={(e) => this.handleChangeText(e)}  id="standard-basic" name="course"  label="Course" />
            </div>
           </div>
           <div className={classes.root} noValidate autoComplete="off">
           <Button type="submit" onClick={this.handleClick} variant="outlined">Submit</Button>
           </div>
            </Typography>
        </div>
      );
    }
  } 

我希望它能对您有所帮助。

答案 1 :(得分:0)

请参阅此完整的最小的完整可验证示例(https://stackoverflow.com/help/mcve | https://stackoverflow.com/help/how-to-ask

CodePen演示:https://codepen.io/Alexander9111/pen/OJVyRvm

使用所有必要的代码来演示所要求的内容:

class WalkInBook extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName:'',
      lastName:'',
      phone:'',
      email:'',
      course:''
    };
    //These lines are important!
    this.handleClick = this.handleClick.bind(this);
    this.handleChangeText = this.handleChangeText.bind(this);
  }
  componentDidMount(){

  }

  handleClick() {
    console.log(this.state);
  }

  handleChangeText(event){
    const target = event.target;
    const value = target.value;
    const name = target.name;
    console.log('change', name, value);
    this.setState({
      ...this.state,
      [name] : value
    })
  }

  render() {
    return (
        <div>
          <input type="text" onChange={this.handleChangeText} name="firstName" placeholder="firstName"/>
          <input type="text" onChange={this.handleChangeText} name="lastName" placeholder="lastName"/>
          <input type="text" onChange={this.handleChangeText} name="phone" placeholder="phone"/>
          <input type="text" onChange={this.handleChangeText} name="email" placeholder="email"/>
          <input type="text" onChange={this.handleChangeText} name="course" placeholder="course"/>
          <button type="submit" onClick={this.handleClick} variant="outlined">Submit</button>
        </div>
        );
    }
} 

ReactDOM.render(
  <WalkInBook />,
  document.getElementById('root')
);

您需要将此.bind(this)绑定到onChange onClick事件处理程序。

此外,您需要使用传播运算符复制现有状态,然后修改一个新属性:

this.setState({
      ...this.state,
      [name] : value
    })

如果您想使用功能组件来完成,并且还要遍历状态以生成输入标签,请查看此(https://codepen.io/Alexander9111/pen/VwLPKvP):

function WalkInBook(props) {
  const initState = {
      firstName:'',
      lastName:'',
      phone:'',
      email:'',
      course:''
    };
  const [state, setState] = React.useState(initState);

  function handleClick() {
    console.log(state);
  }

  function handleChangeText(event){
    const target = event.target;
    const value = target.value;
    const name = target.name;
    console.log('change', name, value);
    setState({
      ...state,
      [name] : value
    })
  }

  const handle = handleChangeText;
  const output = Object.keys(state).map(function (key) {
    //console.log(key)
    return <input type="text" onChange={handle} name={key} placeholder={key}/>;
  });

  return (
    <div>
      {
        output.map((child, index) => {return child})
      }          
      <button type="submit" onClick={handleClick} variant="outlined">Submit</button>
    </div>
  );
} 

ReactDOM.render(
  <WalkInBook />,
  document.getElementById('root')
);

任何问题,让我知道。