2015-07-12 74 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> 
     ); 
    } 
} 
相關問題