2017-09-11 92 views
-1

我想傳遞布爾狀態以將className從一個組件更改爲另一個組件。我試圖通過{this.props.isOpen}傳遞它,但它不起作用。我怎樣才能將狀態值傳遞給另一個組件?將布爾狀態從一個組件傳遞到另一個組件React.JS

父組件

class Category extends React.Component { 
constructor(props) { 
    super(props); 
    this.state={ isOpen: false }; 
    this.handleClick = this.handleClick.bind(this); 
    } 

handleClick() { 
this.setState({ isOpen : !this.state.isOpen }) 
} 

render() { 

const categoryContainer = this.state.isOpen ? "isopen" : ""; 
return(
<div> 
<div className="categoryContainer"> 
    <h3>CATEGORIES</h3> 
</div> 
<button onClick={this.handleClick}>Click</button> 
</div> 
<div className={categoryStatus} id="category"> 
<input className="categoryInput" type="text" value="Add Category" placeholder="Add Category" /> 
    <ul> 
    <li>Greetings</li> 
    <li>Main Switchboard</li> 
    <li>Interjections</li> 
</ul> 
</div> 
<Main isOpen={this.state.isOpen} /> 
</div> 
)} 
} 

輔元件

class Main extends React.Component { 

render() { 
const botStatus = !this.props.isOpen ? "isopen" : ""; 
const botInput = !this.props.isOpen ? "isopen" : ""; 
return (
<div> 
<div className={botStatus} id="bot"> 
    <h2>MASTER INTENTS</h2> 
    <input className={botInput} type="text" value="Add Intent" /> 

</div> 
</div>); 
} 
} 

謝謝你檢查我的問題提前。

+2

我沒有看到Category正在消耗Main。您通常會通過將支柱傳遞給父母的孩子來做到這一點。 – ovation22

回答

1

每當你想從你的父組件(Category)傳遞一個prop的子組件(Main)傳遞給它的render()功能:

render(){ 
    <Main 
    isOpen={this.state.isOpen} 
    /> 
} 

但我沒有看到你導入的孩子組件(Main),或者將其用於父組件的渲染功能(Category)。

爲了將Parent組件的state(甚至props)傳遞給其子組件,您需要在父級渲染函數中使用子組件。

您還可以從React Docs獲得更多信息。

https://facebook.github.io/react/docs/components-and-props.html

+0

感謝您的評論。我想讓它工作這部分'const botStatus =!this.state.isOpen? 「開了」 : 」」; const botInput =!this.state.isOpen? 「isopen」:「」'通過將狀態從父項傳遞給子項。我試着用你的解決方案,但它沒有奏效。該值未在控制檯中打印出來。 – aaayumi

+0

您是否可以在「類別」組件的渲染函數中顯示您將屬性從父項傳遞給子組件的部分的代碼片段?或者更新問題並讓我們知道。 @ayumi – keshavDulal

+0

我把你的代碼片段添加到了'Category'組件中,​​但它還沒有正常工作。 – aaayumi

1

每在React's Thinking陣營文檔,道具是 「從父將數據傳遞到孩子的一種方式。」

爲了您例如,組件Gallery必須包括在渲染功能孩子組件Main,以使其工作。

class Main extends Component { 
    render() { 
     const botStatus = this.props.isOpen ? "isOpen" : "noOpen"; 
     return (
     <div> 
      <div> 
      <h1>{botStatus}</h1> 
      </div> 
     </div> 
    ); 
    } 
    } 

class Gallery extends Component { 
    constructor() { 
     super(); 
     this.state = { 
     isOpen: false 
     }; 
     } 

    render() { 
     return(
      <div> 
      <div> 

       <Main isOpen={this.state.isOpen}/> 

      </div> 
      </div> 
     ); 
    } 
    } 
相關問題