Applying className/onClick/onChange not working on Custom React Component

霸气de小男生 提交于 2019-11-25 22:49:59

The reason is pretty simple, when you onClick like

<Company company={company} key={company.id} onClick={this.editCompany.bind(this)} />

its not an event that is set on the component, rather a prop that is being passed to the Company component and can be accessed like props.company in the Company component,

what you need to do is to specify the onClick event and className in the Company component like

import React, { Component } from 'react';

const Company = ({company, onClick, className}) => (
  <li onClick={onClick} className={className}>
    {company.Nummer} {company.Bezeichnung}
  </li>
)

export default Company

The function passed on as prop to the Company component can be passed on by any name like

<Company company={company} key={company.id} editCompany={this.editCompany.bind(this)} className="Company"/>

and used like

import React, { Component } from 'react';

const Company = ({company, editCompany}) => (
  <li onClick={editCompany}>
    {company.Nummer} {company.Bezeichnung}
  </li>
)

you have to bind the event on you child component :

import React, { Component } from 'react';

const Company = ({ company, onClick }) => 
   <li onClick={onClick}>
      {company.Nummer} {company.Bezeichnung}
   </li>


export default Company

or

const Company = ({ company, ...props }) => 
   <li {...props}>
      {company.Nummer} {company.Bezeichnung}
   </li>

if you want that all props passed to your Compagny component (exept compagny) goes to your li tag. see ES6 spread operator and rest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!