我有以下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>
            ...
        );
    }

};

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


当前回答

功能组件

使用状态

返回一个有状态值和一个更新它的函数。 在初始呈现期间,返回的状态(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>
  );
}

其他回答

最简单的方法是使用箭头函数

箭头函数的代码

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>
        ...
    );
}

};

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

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

然后你会得到标题的结果

你可以在不添加“onChange”函数的情况下获得输入值。

只需在输入元素中添加一个'ref attr:

然后用这个。引用以在需要时获取输入值。

你的错误是因为你使用类,当使用类时,我们需要绑定函数与此,以便工作得很好。不管怎么说,有很多教程告诉我们为什么要用“this”,以及“this”在javascript中是做什么的。

如果你修正了提交按钮,它应该是工作的:

<button type="button" onClick={this.onSubmit.bind(this)} className="btn">Save</button>

如果你想在控制台显示输入值你应该使用var title = this。title。value;

将ref='title'更改为:ref='title'并删除name='title' 然后删除var title = this。标题和写作:

console.log(this.refs.title.value)

此外,你应该添加.bind(this)到this. onsubmit

(它在我的情况下工作,这是非常相似的,但不是onClick,我有onSubmit={…},它被放在form (<form onSubmit={…} > < / >形式)