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

};

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


当前回答

React版本:17.0.1 a)使用功能组件 b)使用hook: useState()管理状态。

编写并运行上面的代码:

import React, {useState} from 'react';

const InputElement = () => {
  const [inputText, setInputText] = useState('');

  return (
   <div> 
        <input
              onChange={(e) => {
                  setInputText(e.target.value);
                   }                   
             }
             placeholder='Enter Text'
       />
       {inputText}
   </div>
 );
}

求解方案算法类似于双向数据绑定:

input <=> DATA_MODEL <=> Label_Text

其他回答

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

箭头函数的代码

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

};

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

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

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

在功能组件中:-

export default function App(){

const [state, setState] = useState({
        value:'',
        show:''
    });

const handleChange = (e) => {
    setState({value: e.target.value})
}

const submit = () => {
    setState({show: state.value})
}

return(
        <>
            <form onSubmit={()=>submit()}>
                <input type="text" value={state.value} onChange={(e)=>handleChange(e)} />
                <input type="submit" />
            </form>
            <h2>{state.show}</h2>
        </>
)}

React版本:17.0.1 a)使用功能组件 b)使用hook: useState()管理状态。

编写并运行上面的代码:

import React, {useState} from 'react';

const InputElement = () => {
  const [inputText, setInputText] = useState('');

  return (
   <div> 
        <input
              onChange={(e) => {
                  setInputText(e.target.value);
                   }                   
             }
             placeholder='Enter Text'
       />
       {inputText}
   </div>
 );
}

求解方案算法类似于双向数据绑定:

input <=> DATA_MODEL <=> Label_Text

给<input>一个唯一的id

<input id='title' ...>

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

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

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