虽然正确定义onClick处理程序,但console.log('hi')不在控制台上打印
import React from 'react';
import './charComponent.css'
const CharOne = (props) =>{
return (<div>
<div className="charOne" onClick={console.log('hi')}>{props.letter}</div>
</div>
)
}
export default CharOne;
答案 0 :(得分:2)
console.log(&#39; hi&#39;)正在立即调用,
所以你的onClick无关(没有工作)。见下面的代码。
import React from 'react';
import ReactDOM from 'react-dom';
const myFunction = () => console.log('hi');
const CharOne = () => <div onClick={myFunction}>Click-Me</div>
ReactDOM.render(<CharOne />, document.getElementById('root'));
如果要传递参数,请使用箭头功能。
import React from 'react';
import ReactDOM from 'react-dom';
const myFunction = props => console.log(props);
const CharOne = () => <div onClick={() => myFunction('Hello')}>Click-Me</div>
ReactDOM.render(<CharOne />, document.getElementById('root'));
答案 1 :(得分:0)
您必须将函数作为参数传递:
import React from 'react';
import './charComponent.css'
const CharOne = (props) =>{
return (<div>
<div className="charOne" onClick={() => console.log('hi')}>{props.letter}</div>
</div>
)
}
export default CharOne;