Onclick组件主要组件的setState()

时间:2017-09-28 11:57:22

标签: javascript reactjs

我正在尝试使用设备组件的当前Devicename onClick设置(MainDevicePicker)状态。

由于某种原因,onClick处理程序无法正常工作,我的console.log()没有显示。

MainDevicePicker.js

import React, { Component } from 'react';

import Device from '../Device/Device';
import './MainDevicePicker.css';

class MainDevicePicker extends Component {
  constructor(){
    super();
    this.selectSubDevice = this.selectSubDevice.bind(this);
    this.state = {
      device: '',
    };
  }

  selectSubDevice(e){
    e.preventDefault();
    console.log('TEST');
    this.setState({
      device: this.props.name,
    })
  }

  render() {
    return (
        <div className="MainDevicePicker">
          <Device name="Mac" fa="apple" onClick={this.selectSubDevice}/>
          <Device name="iPad" fa="apple"/>
          <Device name="iPhone" fa="apple"/>
          <Device name="Laptop" fa="windows"/>
          <Device name="Display" fa="desktop"/>
        </div>
    );
  }
}

export default MainDevicePicker;

Device.js

import React, {Component} from 'react';
import FontAwesome from 'react-fontawesome';
import './Device.css';

class Device extends Component {
  render() {
    return (
        <div className="Device">
          <FontAwesome className='DeviceLogo' name={this.props.fa} />
          <p className="DeviceName">{this.props.name}</p>
        </div>
    );
  }
}

export default Device;

2 个答案:

答案 0 :(得分:1)

您必须将元素绑定到例如:

<Device name="Mac" fa="apple" onClick={this.selectSubDevice.bind(this}/>
设备上的

 return (
    <div className="Device" onClick={this.props.onClick}>
      <FontAwesome className='DeviceLogo' name={this.props.fa} />
      <p className="DeviceName">{this.props.name}</p>
    </div>
);

答案 1 :(得分:0)

我认为您无法在react组件上设置onClick事件。你必须接受&#34; onClick&#34;作为Device类中的prop,并将其传递给您的div,如:

C:\Program Files\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\spyder\utils\ipython\start_kernel.py:5: CalendarHolidayWarning: Holiday list exhausted at end, addbusday(2017-09-22 00:00:00,3) output may be incorrect. # (see spyder/__init__.py for details)

请参阅以下示例: https://pastebin.com/5Dyf1zXC