定义组件
组件就是一个函数,首字母大写
function MyButton() {
const handleClick = (name,e) => {
console.log('my name is not '+ name);
}
return <button onClick={(e) => handleClick('John',e)}>click me !</button>;
}
export default MyButton;
也可以这么写
const MyButton = () => {
const handleClick = (name,e) => {
console.log('my name is not '+ name);
}
return <button onClick={(e) => handleClick('John',e)}>click me !</button>;
}
export default MyButton;
使用组件
关键代码
//导入组件
import MyButton from './MyButton.js'
//使用组件
<MyButton></MyButton>
import MyButton from './MyButton.js'
function App() {
const handleClick = (name,e) => {
console.log('my name is '+ name);
console.log('event object is ',e);
}
return (
<div className="App">
<button onClick={(e)=>handleClick('nas',e)}>点击我一下</button>
<MyButton></MyButton>
</div>
);
}
export default App;