React组件只为构造函数中的一个键设置状态。 ES6

问题描述:

我有这个组件,但它没有在状态构造函数中设置显示。我可以console.log道具和他们显示正确的参数,但出于某种原因,显示没有设置。React组件只为构造函数中的一个键设置状态。 ES6

class SubstitutionPanel extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     suggestions: this.props.synonyms_with_levels, 
     show: this.props.show 
    } 
    } 

    handleToggleShow() { 
    this.setState({ 
     show: false 
    }) 
    } 


    render() { 
    console.log("sub panel") 
    console.log(this.state) 
    console.log(this.props) 
    if (this.props.synonyms_with_levels.length > 0 && this.state.show) { 
     return(
     <div className="substitution-panel"> 
      <div onClick={() => this.handleToggleShow()} className="glyphicon glyphicon-remove hover-hand"></div> 
      {this.props.synonyms_with_levels} 
     </div> 
    );  
    } else { 
     return (
     <span> 
     </span> 
    ); 
    } 
    } 
} 

呈现此子组件的父看起来是这样的:

<SubstitutionPanel synonyms_with_levels= {this.props.synonyms_with_levels} show={this.state.showSubPane} /> 

我真的只是想要做一个“工具提示”里的家长可以打开提示。

+0

你是说'this.state.show'没有显示正确的值,当你console.log它在构造函数中,即使'this.props.show'显示正确的值?或者你的'setState'调用不能正常工作? –

+0

即使我在父项中将它传递为true,this.state.show仍然显示为false。构造函数是设置建议,但不能设置“显示”。 – Josh

+0

它似乎对我来说工作正常:https://jsbin.com/xocebaduwa/edit?js,output你确定'synonyms _with_levels'不是零长度吗? –

当你console.log(this.props)时,一切正常吗?

这可能只是一个错字这里,但在父组件必须

show={this.state.showSubPane} 

,也许它应该是“showSubPanel”有一个L在结束了吗?