<title>react组件定义</title>
</head>
<body>
<div id="app"></div>
<script src="./libs/babel.min.js"></script>
<script src="./libs/react.js"></script>
<script src="./libs/react-dom.js"></script>
<script type="text/babel">
const { useState } = React;
// 组件定义的两种常见形式
// function,无状态组件。此种方法定义的组件没有this指向问题
// 但是在react16.8之后的版本中可以通过hooks实现组件的局部状态和生命周期
// 是目前官方推荐的组件写法
// class,可以继承自React.Component或者React.PureComponent
// 相对来说继承自PureComponent的组件性能更快一些
function Count(props) {
// props叫什么都可以,可以起其他的名字,但是要和下面使用到的时候保持一致,但是为了规范易懂,就用了props
console.log(props);
// const { step } = props;
const step = props.step || 1;
// useState可以在function定义的组件中设置一个局部状态(如setCount),这个局部状态可以改变它的内容,其定义好之后,可以随着组建的存在而一直存在
// 此方法返回一个数组
// 第一个值为 可以在当前组件中使用的变量名
// 第二个值表示改变当前数据的方法
// [count, setCount] 这是一个解构赋值
const [count, setCount] = useState(0);
// const [count, setCount] = React.useState(0);
/* const [title, setTitle] = useState("当前标题");
const keyUpHandle = (e) => setTitle(e.target.value); */
const [list, setList] = useState([]);
const keyUpHandle = (e) => {
if (e.keyCode === 13) {
/* 这个方法看似可以,但是不能使用这个方法,因为你输入值的时候,
从打印台中可以看到(谷歌上的一个react插件:React Developer Tools
),你虽然输进去了,但是在页面中并不会更新显示,
所以不能这么用
list.push({ id: Date.now(), content: e.target.value });
setList(list); */
setList([{ id: Date.now(), content: e.target.value }, ...list]);
}
};
return (
<div>
<h5>当前的步长为:{step}</h5>
<ul>
{list.map((item) => (
<li key={item.id}>{item.content}</li>
))}
</ul>
<input type="text" placeholder="请输入内容" onKeyUp={keyUpHandle} /* onKeyUp={(e) => e.target.value} *//>
<button onClick={() => setCount(count + step)}>
计数值为:{count}
</button>
</div>
);
}
ReactDOM.render(
<div>
<Count step={5} />
<Count step="5" />
<Count />
<Count />
</div>,
document.getElementById("app")
);
</script>
</body>