下面看看这两个变化:
- import React, { useState } from 'react';
- import './List.css';
- const ListItem = ({ action, title, setClicked }) => {
- return {
- <li>
- <button
- onClick={() => {
- setclicked(title);
- action();
- }}
- className="my-button">
- {title}
- </button>
- </li>
- );
- };
- const List = ({ create, read, update, destroy }) => {
- const [clicked, setClicked] = useState('');
- return (
- <div>
- <hl>The last clicked button is {clicked}</hl>
- <ul>
- <ListItem title="Create" action={create} setClicked={setClicked} />
- <ListItem title="Read" action={read} setClicked={setClicked} />
- <ListItem title="Update" action={update} setClicked={setClicked} />
- <ListItem title ="Destroy" action={destroy} setClicked={setClicked} />
- </ul>
- </div>
- );
- };
太好了,我们大大减少了组件声明的长度,但是我们仍然可以做得更好!
4. 愿 PropTypes 与你同在!
经过清理之后,该是用到编写组件时最棒的实践的时候了!使用 PropTypes,我们可以验证接收到的 props,以避免由于不同数据类型而导致的错误。例如,接收字符串“0”并尝试将其与数字 0 严格对比(“0” === 0-> FALSE!!!):
- import React, { useState } from 'react';
- import PropTypes from 'prop-types';
- const ListItem = ({ action, title, setClicked }) => {
- return (
- <li>
- <button
- onClick={() => {
- setClicked(title);
- action();
- }}
- className="my-button">
- {title}
- </button>
- </li>
- );
- };
- ListItem.propTypes = {
- action: PropTypes.func,
- setClicked: PropTypes.func,
- title: PropTypes.string
- };
- const List = ({ create, read, update, destroy }) => {
- const [clicked, setClicked] = useState('');
- return (
- <div>
- <hl>The last clicked button is {clicked}</hl>
- <ul>
- <ListItem title="Create" action={create} setClicked={setClicked} />
- <ListItem title="Read" action={read} setClicked={setClicked} />
- <ListItem title="Update" action={update} setClicked={setClicked} />
- <ListItem title ="Destroy" action={destroy} setClicked={setClicked} />
- </ul>
- </div>
- );
- };
- List.propTypes = {
- create: PropTypes.func,
- read: PropTypes.func,
- update: PropTypes.func,
- destroy: PropTypes.func,
- };
- export default List;
PropTypes 验证
5. 切成小块
想不到吧——我们现在的组件与初始版本差不多一样长,但请仔细观察我们现在手上的代码。
我们看到了两个不同的组件,可以将它们划分为两个模块,从而使它们在整个应用程序中都能复用。
- import React, { useState } from 'react';
- import PropTypes from 'prop-types';
- import ListItem from './ListItem.js'
- const List = ({ create, read, update, destroy }) => {
- const [clicked, setClicked] = useState('');
- return (
- <div>
- <hl>The last clicked button is {clicked}</hl>
- <ul>
- <ListItem title="Create" action={create} setClicked={setClicked} />
- <ListItem title="Read" action={read} setClicked={setClicked} />
- <ListItem title="Update" action={update} setClicked={setclicked} />
- <ListItem title ="Destroy" action={destroy} setClicked={setclicked} />
- </ul>
- </div>
- );
- };
- };
- List.propTypes = {
- create: PropTypes.func,
- read: PropTypes.func,
- update: PropTypes.func,
- destroy: PropTypes.func,
- };
- export default List;
(编辑:青岛站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|