javascript 反应复选框并选择 onChange

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49212020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:28:31  来源:igfitidea点击:

React Checkbox & Select onChange

javascriptreactjsmaterialize

提问by Chris Hurst

I've read plenty of question on this subject & gone over the documentation for React as well, but I'm still no wiser this. I cannot get an input field to emit anything (an event) on click or change.

我已经阅读了很多关于这个主题的问题,并且还浏览了 React 的文档,但我仍然不知道这一点。我无法让输入字段在单击或更改时发出任何内容(事件)。

My code is below and other than using materialzecss, I'm using basic HTML/JSX & no other javascript.

我的代码在下面,除了使用 materialzecss,我使用的是基本的 HTML/JSX 而没有其他 javascript。

I'm simply unable to update the input to toggle between checked/not-checked on either onChange or onClick. Can anybody tell me where I'm going wrong here?

我只是无法更新输入以在 onChange 或 onClick 上的选中/未选中之间切换。谁能告诉我我哪里出错了?

import React, { Component } from 'react'
import Alert from '../components/shared/Alert'
import { Redirect } from 'react-router-dom'
import axios from 'axios'

class Create extends Component {
  constructor(){
    super()
    this.state = {
      redirect:false,
      alert:{
        show: false
      },
      checked:true
    }
  }

  handleChange(event) {
    this.setState({
      recipe : {[event.target.name]: event.target.value}
    })
    console.log(this.state);

  }

  handleSubmit(event) {

  }


  render() {
    const { redirect } = this.state;
    const showAlert = this.state.alert.show;
     if (redirect) {
       return <Redirect to='/'/>;
     } else if (showAlert) {
        console.log("alert");
     }
    return (
      <div className="row">
        {showAlert ? <Alert /> : ''}
        <div className="container">
          <div className="row">
              <div className="col s10 offset-s1  z-depth-1" id="loginForm">
              <h5 className="red darken-4" id="title">Create New Recipe</h5>
              <form >
                <div className="input-field" id="username" >
                  <input type="text" className="validate" name="name"
                  onChange={this.handleChange.bind(this)} />
                  <label htmlFor="name">Name</label>
                </div>
                <div className="input-field" id="password">
                  <input type="text" className="validate" name="intro" 
                  onChange={this.handleChange.bind(this)} />
                  <label htmlFor="password">Intro</label>
                </div>
                <div className="input-field" id="password">
                  <textarea id="textarea1" className="materialize-textarea" name="body" 
                  onChange={this.handleChange.bind(this)}>
                  </textarea>
                  <label htmlFor="textarea1">Recipe</label>
                </div>
                <div className="row">
                  <div className="input-field col s12 m5" id="password">
                    <Serves function={this.handleChange.bind(this)}/>
                    <label>Serves</label>
                  </div>
                  <div className="input-field col s12 m5" id="test">
                    <select name="cuisine" defaultValue="2" onChange={(e)=>{console.log(e)}}>
                      <option value="1">1</option>
                      <option value="2">2</option>
                      <option value="3">3</option>
                    </select>
                    <label>Cuisine</label>
                  </div>
                </div>
                <div className="input-field" id="password">
                  <input type="checkbox" className="filled-in" id="filled-in-box"/>
                  <label htmlFor="filled-in-box">Public?</label>
                </div>
              <button type="submit" className="waves-effect waves-light btn red darken-4" id="loginbtn">Login</button>
              <a href="/app/dashboard" className="waves-effect waves-light btn amber darken-1" id="loginbtn">Back</a>
            </form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Create;

const Serves = (props) => {
  return(
    <select onChange={props.function} name="serves" >
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="9">10</option>
    </select>
  )
}

回答by Andrew Heekin

You need to add the checkedattribute to the input field and set it equal to the state property you are changing

您需要将checked属性添加到输入字段并将其设置为等于您正在更改的状态属性

add this method:

添加此方法:

handleCheckClick = () => {
  this.setState({ checked: !this.state.checked });
}

and change the checkbox jsx:

并更改复选框 jsx:

<input type="checkbox" checked={this.state.checked} onChange={this.handleCheckClick} className="filled-in" id="filled-in-box"/>

回答by bukharim96

Make use of refs:

使用参考:

<select onChange={props.function} ref="serves" >
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="9">10</option>
    </select>

And now in your props.functionget the selecttag's value with: this.refs.serves.value.

现在在您使用以下方法props.function获取select标签的值:this.refs.serves.value

For more info on refscheckout this.

有关更多信息refs结帐这个

回答by giggi__

You have to set the value attribute on the input to se the setted value. It has to be equality to this.state.{inputName}. And use The bindings in constructor, is the preferred approach.

您必须在输入上设置 value 属性以设置设置的值。它必须与 this.state.{inputName} 相等。并在构造函数中使用绑定,是首选方法。