2015-05-17 123 views
1

好的,所以我開始讓我的頭繞着ReactJs,但一直被一個簡單的概念困擾着,它是一個簡單的舊jQuery的簡單概念。從一個反應組件向另一個反應組件注入內容onClick

我希望能夠在點擊事件發生在另一個元素上時添加到屏幕上的一個元素的內容。在react tutorial之後,我完全理解他們已經實現了添加到評論列表的方式,評論列表是父母的設置狀態的孩子..但肯定這不是唯一的方式,因爲它感覺非常僵硬和僵化。

下面是我想解釋的一個簡單模型。在按鈕的點擊,我想注入新的內容到DIV ID爲「newComments」 .. JSBin:http://jsbin.com/vokufujupu/1/edit

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>JS Bin</title> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script> 
</head> 
<body> 
    <div id="content"></div> 
    <script type="text/jsx"> 

     var InputBox = React.createClass({ 
      clickHandler: function(){ 
       //Append a new string to the end of the existing copy in the copy box 
       alert('after this alert the value of the button should be appended to the content of the div#newComments'); 

      }, 
      render: function() { 
       return (
         <div classNmae="copyBox"> 
          <input type="button" name="inputButton" value="click me button" className="bbbc" 
          onClick={this.clickHandler} /> 
         </div> 
      ); 
      } 
     }); 

     var CopyBox = React.createClass({ 
      render: function() { 
       return (
       <div classNmae="copyBox"> 
        <p>div#newComments:</p> 
        <div id="newComments"></div> 
       </div> 
      ); 
      } 
     }); 

     var Page = React.createClass({ 
      render: function() { 
       return (
        <div> 
         <CopyBox/> 
         <InputBox/> 
        </div> 
      ); 
      } 
     }); 

     React.render(
       <Page/>, 
       document.getElementById('content') 
    ); 

    </script> 

    <!-- The equiv in plain old js --> 
    <script type="text/javascript"> 
    function newContent(obj){ 
     document.getElementById('vanBox').innerHTML = document.getElementById('vanBox').innerHTML + obj.value; 
    } 
    </script> 
    <div id="vanilaJsEquiv"> 
    <div id="vanBox"></div> 
    <input type="button" value="ClickyClik" onclick="newContent(this)"/> 
    </div>  

</body> 
</html> 

我一直在四處狩獵谷歌及yonks的文檔,並不能找到答案..

回答

1

在反應沒有操縱HTML/DOM的概念。 React只負責基於組件狀態進行渲染。每個組件呈現任何當前狀態。因此你需要操縱其他組件的狀態。爲此,Facebook使用Flux。這是一個更復雜的工作流程,但一旦你得到它,它實際上是非常簡單的概念。

在其中一個組件上點擊發送一個動作。該操作將觸發事件,訂閱該事件的商店將作出反應並更新內部狀態。更新後,商店發出更改事件,監聽該商店中更改的所有組件都將更新。

是的,你需要編寫更多的代碼。如果組件正在操作它自己的狀態,它會變得更簡單,那麼只需在組件內部調用this.setState({ ... })即可。是的,有其他方法可以做到這一點。