如何使用功能组件在道具中传递参数

时间:2017-12-27 09:18:52

标签: reactjs

如何使用功能组件在props中传递参数,这里我给出了我的工作示例代码, 让我解释一下,当我点击PopUpHandle我需要从PopUpHandle组件中获取值时,我的点击事件将从ContentSection触发。当点击每个列表时,ContentSection将成为列表,以获取当前点击列表的value。我尝试使用此代码console打印undefined,但我不知道如何处理功能组件。

class mainComponent extends Component {
    constructor(props) {
        super(props);
        this.popTrigger = this.popTrigger.bind(this);
    }

    popTrigger(data){
        console.log(data);
    }

    render(){
        return(
            <Popup popTrigger={this.popTrigger} />
        )
    }
}
export default mainComponent;

弹出组件

const PopUpHandle = ({ popTrigger, value}) => <li onClick={popTrigger.bind(this, value)} />;

const ContentSection =({popTrigger, value}) =>(
    <div>
        {value === 'TEST1' && (
        <div>
            <PopUpHandle popTrigger={popTrigger} value={value} />
          </div>
        </div>
        )}
        {value === 'TEST2' && (
        <div>
            <PopUpHandle popTrigger={popTrigger} value={value} />
          </div>
        </div>
        )}
    </div>
)

const ContentList = (({ items, popTrigger}) => (
    <div>
      {items.map((value, index) => (
        <ContentSection
          key={`item-${index}`}
          popTrigger={popTrigger}
          index={index}
          value={value}
        />
      ))}
    </div>
  )
);

    class example extends Component {
    constructor(props) {
        super(props);
        this.state = {
          items: ['TEST1', 'TEST2', 'TEST3', 'TEST4'],
        };
        this.popTrigger = this.popTrigger.bind(this);
    }

    popTrigger(){
        this.props.popTrigger()
    }

    render(){
        return(
            <ContentList popTrigger={this.popTrigger} items={this.state.items} />
        )
    }
}
export default example;

2 个答案:

答案 0 :(得分:1)

<canvas id="bar-canvas"></canvas>

调用 popTrigger(data){ console.log(data); } 时未通过data。在javascript中如果你没有传递参数,它会将其视为this.props.popTrigger()

答案 1 :(得分:0)

[u'', u'', u'', u'', u'RS2 WW10 BKC', u'', u'RS2 WW23.2 BKC', u''] [u'Slno', u'Title', u'Platform Target(W)', u'SoC Target (mW)', u'Platform Power( W)', u'SoC Power (W)', u'Platform Power(W)', u'SoC Power (W)'] [u'', u'', u'', u'', u'', u'', u'', u''] [1.0, u'Display Idle', 4766.0, 80.0, 5013.0, 145.0, 2714.0, 2422.0] [2.0, u'VPB 1080p_30fps', 4999.0, 615.0, 4726.0, 1219.0, 2800.0, 2470.0] [3.0, u'VPB _4k2k-H265', 5888.0, 1231.0, 5244.0, 1619.0, 0.0, 0.0] [4.0, u'Connected standby', 181.0, 17.0, 266.0, 124.0, 176.0, 74.0] [5.0, u'S3', 193.0, 52.0, 132.0, 94.0, 3719.0, 3245.0] [6.0, u'Angry Bird', 6804.0, 2118.0, 7730.0, 3860.0, 2668.0, 2387.0] [7.0, u'Browsing bench', 6209.0, 474.0, 5851.0, 1241.0, 3207.0, 2813.0] [8.0, u'Dash Streaming', 5411.0, 663.0, 5576.0, 1842.0, 0.0, 0.0] [9.0, u'MM14', 5651.0, 973.0, 7504.0, 3024.0, 0.0, 0.0] [10.0, u'Miracast-VPB_Extend', 5072.0, 4007.0, 4196.0, 3081.0, 0.0, 0.0] [11.0, u'Miracast-Idle', 5389.0, 756.0, 0.0, 0.0, 0.0, 0.0] 组件未传递ContentSection道具,因此未传递给value组件。传递它

PopUpHandle