React

export default ({ name = '小明', sex = '男' }) => (
  <>
    我叫 {name},性别 {sex}
  </>
);
// 错误
<MyInput inputValue onInputChange wrapStyle wrapClassName />

// 正确
<MyInput value onChange style className />
// 错误:
render() {
  const obj = {num: 1}

  return (
    <Child obj={obj} onClick={()=>{...}} />
  );
}
// 错误:
render() {
  const a = 8;
  return (
    <div>
      {
        a > 0 ? a < 9 ? ... : ... : ...
      }
    </div>
  );
}
// 正确:
f() {
  // ...
}

render() {
  const a = 8;

  return (
    <div>
      {
        this.f()
      }
    </div>
  );
}

例如:

{
  loading ? <Loading /> : null;
}

可简化为

{
  loading && <Loading />;
}
import React from 'react';

export default function SampleComponent({ onValueChange }) {
  const handleChange = (key) => {
    return (e) => onValueChange(key, e.target.value);
  };

  return (
    <form>
      <input onChange={handleChange('name')} />
      <input onChange={handleChange('email')} />
      <input onChange={handleChange('phone')} />
    </form>
  );
}
// 组件
import React, { useCallback, useState } from 'react';
import ConfirmationDialog from 'components/global/ConfirmationDialog';

export default function useConfirmationDialog({ headerText, bodyText, confirmationButtonText, onConfirmClick }) {
  const [isOpen, setIsOpen] = useState(false);

  const onOpen = () => {
    setIsOpen(true);
  };

  const Dialog = useCallback(
    () => (
      <ConfirmationDialog
        headerText={headerText}
        bodyText={bodyText}
        isOpen={isOpen}
        onConfirmClick={onConfirmClick}
        onCancelClick={() => setIsOpen(false)}
        confirmationButtonText={confirmationButtonText}
      />
    ),
    [isOpen]
  );

  return {
    Dialog,
    onOpen,
  };
}
// 使用
import React from 'react';
import { useConfirmationDialog } from './useConfirmationDialog';

function Client() {
  const { Dialog, onOpen } = useConfirmationDialog({
    headerText: 'Delete this record?',
    bodyText: 'Are you sure you want delete this record? This cannot be undone.',
    confirmationButtonText: 'Delete',
    onConfirmClick: handleDeleteConfirm,
  });

  function handleDeleteConfirm() {}

  const handleDeleteClick = () => {
    onOpen();
  };

  return (
    <div>
      <Dialog />
      <button onClick={handleDeleteClick} />
    </div>
  );
}

export default Client;

这种模式可以少写很多与组件相关的 state,比如弹窗的 visible、title 之类的

// 例如:
import React from 'react';
import ItemDisplay from './ItemDisplay';

export default function SampleComponent() {
  const { data, handleDelete, handleEdit, handleAdd } = useCustomHook();

  return (
    <div>
      <div>
        {data.map((item) => (
          <ItemDisplay item={item} />
        ))}
      </div>
      <div>
        <button onClick={handleDelete} />
        <button onClick={handleAdd} />
        <button onClick={handleEdit} />
      </div>
    </div>
  );
}