2015-07-12 50 views
1

所以我有下面的代码,它利用自举的按钮造型和功能:如何将数据从元素传递到ReactJS中的操作?

import React from 'react'; 

import DashboardActions from '../../action/dashboard.js'; 

export class StatFilter extends React.Component 
{ 
    constructor(props) { 
     super(props); 
     this.state = { 
      selection: this.props.initialSelection 
     }; 
    } 

    render() { 
     return (
      <div className="btn-group"> 
       <button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown" 
         onChange={DashboardActions.seeValue.bind(null, React.findDOMNode(this.refs.viewButton).value)}> 
        <span>{this.props.initialSelection}</span> 
        <span className="caret"></span> 
        <span className="sr-only">Toggle Dropdown</span> 
       </button> 
       <ul className="dropdown-menu"> 
        <li><a>Revenue</a></li> 
        <li><a>Trends</a></li> 
        <li><a>Statistics</a></li> 
       </ul> 
      </div> 
     ); 
    } 
} 

里面的render功能,我StatFilter附加到事件的动作。我想要发生的那个绑定是viewButton按钮的值被传递给动作。换句话说,当按钮的值发生变化时,StatFilter将发送一个动作,让我的应用程序知道其值已更改。

我如何做到这一点是通过使用bind()viewButton的值传递给操作。然而,这给我的警告:

t is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.

和错误:

Uncaught TypeError: Cannot read property 'value' of null

虽然我敢肯定,我这样做不对,就是警告,告诉我什么呢?我应该在渲染函数中处理所有这些逻辑吗?如果不是,那我应该把它放在哪里?另外,上面的代码怎么不起作用?

+0

为什么-1?我做了我的研究。 –

回答

2

在render方法内调用findDOMNode返回是问题。您不能直接在事件处理函数中调用函数,而是必须通过事件处理函数回调。这不会在组件呈现时调用函数调用,而是在事件发生时调用。

export class StatFilter extends React.Component 
{ 
    constructor(props) { 
     super(props); 
     this.state = { 
      selection: this.props.initialSelection 
     }; 
    } 
    handleChange(){ 
     DashboardActions.seeValue(React.findDOMNode(this.refs.viewButton).value); 
    } 
    render() { 
     return (
      <div className="btn-group"> 
       <button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown" 
         onChange={this.handleChange}> 
        <span>{this.props.initialSelection}</span> 
        <span className="caret"></span> 
        <span className="sr-only">Toggle Dropdown</span> 
       </button> 
       <ul className="dropdown-menu"> 
        <li><a>Revenue</a></li> 
        <li><a>Trends</a></li> 
        <li><a>Statistics</a></li> 
       </ul> 
      </div> 
     ); 
    } 
} 
相关问题