2017-07-12 46 views
-1

在我的组件中,我有两个按钮,我希望onClick函数根据组件状态进行更改。是否可以分配函数参考以反应状态?

是否可以分配函数引用状态变量?

例如

constructor() { 
     this.foo = this.foo.bind(this); 
     this.bar = this.bar.bind(this); 
     this.state = { 
     buttonMessage: "hello", 
     buttonFunction: foo 
     } 
     } 

    foo() { 
     this.setState({ 
     buttonFunction: bar 
     }) 
    } 

    bar() { 
     this.setState({ 
     buttonFunction: foo 
     }) 
    } 
    } 

当我尝试上面的代码,我得到一个错误说没有定义的foo和酒吧。也许这只是一个语法错误?很高兴知道是否可以将函数引用分配给状态变量。

+1

为什么不试一试? –

+0

我做了,我得到的错误,没有定义foo。也许这是语法,也许不是。这就是我问的原因。 – Flux

+1

没错,但这与国家无关。你需要'buttonFunction:this.bar' –

回答

0

从评论中的讨论中得出的简单回答可以归结为原始问题:是的,这是可能的。

我在我的例子中遇到的问题是我忘记在分配函数引用this.setState({buttonFunction: foo})时使用“this”,它应该是this.setState({buttonFunction: this.foo})

下面的代码将工作:

constructor() { 
     this.foo = this.foo.bind(this); 
     this.bar = this.bar.bind(this); 
     this.state = { 
     buttonMessage: "hello", 
     buttonFunction: this.foo 
     } 
     } 

    foo() { 
     this.setState({ 
     buttonFunction: this.bar 
     }) 
    } 

    bar() { 
     this.setState({ 
     buttonFunction: this.foo 
     }) 
    } 
    } 

非常感谢尤里Tarabanko提供援助。

1

这是你想要的东西吗?

// import React from 'react'; 
 

 
class HelloKitty extends React.Component { 
 
    constructor(args) { 
 
    super(args); 
 
    this.foo = this.foo.bind(this); 
 
    this.bar = this.bar.bind(this); 
 

 
    this.state = { 
 
     buttonMessage: "hello", 
 
     buttonFunction: this.foo 
 
    }; 
 
    } 
 

 
    foo() { 
 
    this.setState({ 
 
     buttonFunction:() => alert('foo'), 
 
    }) 
 
    } 
 

 
    bar() { 
 
    this.setState({ 
 
     buttonFunction:() => alert('bar'), 
 
    }) 
 
    } 
 

 

 
    render() { 
 
    return (
 
     <div className="root"> 
 
     <div> 
 
      <span onClick={this.foo}>I'am foo</span> 
 
      <span onClick={this.bar}>I'am bar</span> 
 
     </div> 
 

 
     <span onClick={this.state.buttonFunction}>{this.state.buttonMessage}</span> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <HelloKitty />, 
 
    document.getElementById('container') 
 
);
.root { 
 
    display: flex; 
 
    flex-direction: column; 
 
    width: 50%; 
 
} 
 
    
 
.root div { 
 
    display: flex; 
 
    justify-content: space-between; 
 
} 
 

 
span { 
 
    border: 1px solid black; 
 
    margin: 30px; 
 
    padding: .5em; 
 
    width: 100px; 
 
    cursor: pointer; 
 
} 
 
span:hover { 
 
    background-color: #8f8; 
 
}
<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=container></div>

+0

差不多,不完全。我也希望onclick函数是this.state.buttonFunction – Flux

相关问题