2017-06-15 106 views
1

我有一個像這樣構建的React組件,它從父組件中接收回調函數。當火的onClick,它調用從項目的值回調映射過來:將值從父組件傳遞到回調函數而不進行綁定

class Child extends Component { 
    static propTypes = { 
    ... 
    } 

    render =() => { 
    return (
     <div> 
     {this.props.data.map((el, idx) => { 
      return <section onClick={() = this.props.cb(el.val)}></section> 
     } 
     )} 
     </div> 
    ); 
    } 

} 

什麼我不知道是我怎麼能做到通過從map回調的值,而無需使用此語法() => this.props.cb(item.val)或將值綁定到回調。我不能將回調傳遞給onClick,因爲它會立即觸發值。

當前的語法有效,但打破了我在我的linter中設置的規則。

+1

看https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md#lists-of-items – Hamms

回答

2

render結合的另一種方法是打破了一個新的組件,它需要回調和值傳遞:

class Section extends React.Component { 
    handleClick =() => { 
    this.props.onClick(this.props.val) 
    } 
    render() { 
    return <section onClick={this.handleClick}></section> 
    } 
} 

(我建議只禁用皮棉規則,雖然)