我有以下React组件:

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        var title = this.title;
        console.log(title);
    }

    render(){
        return (
            ...
            <form className="form-horizontal">
                ...
                <input type="text" className="form-control" ref={(c) => this.title = c} name="title" />
                ...
            </form>
            ...
            <button type="button" onClick={this.onSubmit} className="btn">Save</button>
            ...
        );
    }

};

控制台给了我未定义-有人知道这段代码有什么问题吗?


当前回答

使用不受控字段:

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        console.log(e.target.neededField.value);
    }

    render(){
        return (
            ...
            <form onSubmit={this.onSubmit} className="form-horizontal">
                ...
                <input type="text" name="neededField" className="form-control" ref={(c) => this.title = c}/>
                ...
            </form>
            ...
            <button type="button" className="btn">Save</button>
            ...
        );
    }

};

其他回答

如果你使用类组件,那么只有3个步骤-首先你需要为你的输入文件声明状态,例如这个。State = {name: "}。其次,你需要写一个函数来设置状态,当它在下面的例子中发生变化时,它是setName(),最后你必须写输入jsx,例如< input value={this.name} onChange ={this.setName}/>

import React, { Component } from 'react'

export class InputComponents extends Component {
    constructor(props) {
        super(props)

        this.state = {
             name:'',
             agree:false
        }
        this.setName = this.setName.bind(this);
        this.setAgree=this.setAgree.bind(this);
    }

    setName(e){
        e.preventDefault();
        console.log(e.target.value);
        this.setState({
            name:e.target.value
        })
    }
    setAgree(){
        this.setState({
            agree: !this.state.agree
        }, function (){
            console.log(this.state.agree);
        })
    }
    render() {
        return (
            <div>
                <input type="checkbox" checked={this.state.agree} onChange={this.setAgree}></input>
                < input value={this.state.name} onChange = {this.setName}/>
            </div>
        )
    }
}

export default InputComponents

你应该在MyComponent extends React类下使用构造函数。组件

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

然后你会得到标题的结果

给<input>一个唯一的id

<input id='title' ...>

然后使用标准的Web API在DOM中引用它

const title = document.getElementById('title').value

不需要在每次按键时不断更新React状态。只需在需要时获取值即可。

// On the state
constructor() {
  this.state = {
   email: ''
 }
}

// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}

<Input 
  value={this.state.email ? this.state.email : ''} 
  onChange={event => this.setState({ email: event.target.value)}
  type="text" 
  name="emailAddress" 
  placeholder="johdoe@somewhere.com" />

功能组件

使用状态

返回一个有状态值和一个更新它的函数。 在初始呈现期间,返回的状态(state)与作为第一个参数传递的值(initialState)相同。 setState函数用于更新状态。它接受一个新的状态值,并对组件的重新呈现进行排队。 SRC——> https://reactjs.org/docs/hooks-reference.html#usestate

useRef

useRef返回一个可变的ref对象,其.current属性初始化为传递的参数(initialValue)。返回的对象将在组件的整个生命周期内持续存在。 SRC——> https://reactjs.org/docs/hooks-reference.html#useref

import { useRef, useState } from "react";

export default function App() {
  const [val, setVal] = useState('');
  const inputRef = useRef();

  const submitHandler = (e) => {
    e.preventDefault();

    setVal(inputRef.current.value);
  }

  return (
    <div className="App">
      <form onSubmit={submitHandler}>
        <input ref={inputRef} />
        <button type="submit">Submit</button>
      </form>

      <p>Submit Value: <b>{val}</b></p>
    </div>
  );
}