如何访问组件中的道具?

时间:2016-05-16 08:37:31

标签: reactjs

是否可以在myVar内访问handleClick值?仍在努力让基础知识正确:-)。尝试在{myVar}内传递但仍然相同。

var Button = React.createClass({
    getInitialState(){
      return {counter: 1}
    },
    handleClick(){
      console.log(this.props.myVar); //getting undefined here
    },
    render(){
        return(
            <button onClick={this.handleClick} myVar="blah">{this.state.counter}</button>
        );
    }
});

4 个答案:

答案 0 :(得分:2)

道具在您的组件的任何位置都可用,这意味着您无需将其作为道具传递给button标签。只是一个正确绑定的函数将为您处理,并且因为您使用.createClass(),您的函数会自动绑定到组件的实例,这意味着 handleClick函数已经可以访问this.propsthis.state

handleClick: function (event) {
   console.log(this.props.myVar); //blah
}

但是如果要将额外的变量传递给函数handleClick,则需要将新函数传递给onClick处理程序。请记住绑定this,以便您也可以访问您的实例

handleClick: function (event, myVar) {
   console.log(myVar);
}

<button onClick={this.handleClick.bind(this, myVar)} />

答案 1 :(得分:1)

属性绑定到组件本身,因此this.props将始终指向通过父级添加的属性,而不是像angular指令那样标记的每个部分。要将变量绑定到onclick,您可以这样做:

<button onClick={() => this.handleClick("blah")}>{this.state.counter}</button>

Then youre handleclick will fetch it as its first parameter. 

你当然可以创建自己的按钮组件,然后像你一样传递道具。然后按钮组件将包含this.props.myVar

答案 2 :(得分:1)

您可以将变量和访问绑定为handleClick函数中的参数:

 var Button = React.createClass({
  getInitialState(){
  return {counter: 1}
},
handleClick(myVar){
  console.log(myVar) //consoles blabh; 
},
render(){
   let myVar="blabh";
    return(
        <button onClick={this.handleClick.bind(myVar)} >{this.state.counter}    </button>
       );
    }
 });

答案 3 :(得分:-1)

事情是默认情况下事件没有绑定到您的组件,所以要修复它只是将处理程序绑定到此。

<button onClick={this.handleClick.bind(this)} myVar="blah">{this.state.counter}</button>
相关问题