use*_*461 0 javascript reactjs
我想在另一个方法中调用一个方法,但是它永远不会被调用.
按钮:
<span onClick={this.firstMethod()}>Click me</span>
Run Code Online (Sandbox Code Playgroud)
零件:
class App extends Component {
constructor(props) {
super(props);
this.state = {..};
}
firstMethod = () => (event) => {
console.log("button clicked")
this.secondMethod();
}
secondMethod = () => (event) => {
console.log("this is never called!")
}
render() {..}
}
Run Code Online (Sandbox Code Playgroud)
调用第一种方法,但不是第二种方法.我试图添加到构造函数
this.secondMethod = this.secondMethod.bind(this);
Run Code Online (Sandbox Code Playgroud)
这在所有其他解决方案中都是推荐的,但似乎没有什么对我有用.如何正确调用第二种方法?
这里有两个问题.
第一个:你错误地定义了你的功能.
firstMethod = () => (event) => {
console.log("button clicked")
this.secondMethod();
}
Run Code Online (Sandbox Code Playgroud)
像这样,您将从函数返回另一个函数.所以,它应该是:
firstMethod = ( event ) => {
console.log("button clicked")
this.secondMethod();
}
Run Code Online (Sandbox Code Playgroud)
第二:您没有使用onClick处理程序,而是立即调用该函数.
<span onClick={this.firstMethod()}>Click me</span>
Run Code Online (Sandbox Code Playgroud)
所以,这应该是:
<span onClick={() => this.firstMethod()}>Click me</span>
Run Code Online (Sandbox Code Playgroud)
如果您使用的是第一个版本,那么当组件第一次立即运行时会运行,但点击不起作用.onClick需要一个处理程序
在这里,我完全同意@Danko的评论.你应该将它onClick与函数引用一起使用.
<span onClick={this.firstMethod}>Click me</span>
Run Code Online (Sandbox Code Playgroud)
使用此方法,每次组件呈现时都不会重新创建函数,因为它使用处理函数及其引用.此外,没有努力手动编写处理程序.
最后,如果将函数定义为箭头函数,则不需要.bind它们.
这是工作代码.
class App extends React.Component {
firstMethod = () => {
console.log("button clicked")
this.secondMethod();
}
secondMethod = () =>
console.log("this is never called!")
// or maybe even better not using an arrow function for the
// second method since it is already bound to `this` since we
// invoke it from the firstMethod. For details, look the comments please.
/* secondMethod() {
console.log("this is never called!")
} */
render() {
return(
<span onClick={this.firstMethod}>Click me</span>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |