我正在学习React中的状态概念。我试图了解使用this.handleChange和this.state.handleChange之间的区别。
如果有人可以向我解释两者之间的确切区别,以及为什么this.state.handleChange不起作用,我将不胜感激。
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
< GetInput input={this.state.inputValue} handleChange={this.handleChange} />
{ /* this.handleChanges, and this.state.handleChanges */ }
< RenderInput input={this.state.inputValue} />
</div>
);
}
};
class GetInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Get Input:</h3>
<input
value={this.props.input}
onChange={this.props.handleChange}/>
</div>
);
}
};
class RenderInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Input Render:</h3>
<p>{this.props.input}</p>
</div>
);
}
};
最佳答案
只要您在状态中添加this.state.handleChange
,就可以从技术上调用handleChange
。
但这并没有什么意义,因为您不希望React跟踪它,并且它可能不会改变(除非您正在做一些clever
技巧)。
constructor(props) {
super(props);
this.state = {
handleChange: e => {
e.preventDefault();
console.log("this.state.handleChange");
}
};
}
通常可以在一个类中声明一个成员函数。
handleChange = e => {
e.preventDefault();
console.log("this.handleChange");
};
这是完整的工作代码
(可以在CodeSandBox上获得工作演示)。
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
handleChange: e => {
e.preventDefault();
console.log("this.state.handleChange");
}
};
}
handleChange = e => {
e.preventDefault();
console.log("this.handleChange");
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={this.handleChange}>this.handleChange</button>
<button onClick={this.state.handleChange}>
this.state.handleChange
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
关于javascript - ReactJS中this.state.function和this.function有什么区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51451653/