简体   繁体   English

如何在反应功能组件中声明默认道具

[英]How to declare default props in react functional component

I want to declare default props in a functional component我想在功能组件中声明默认道具

normally we would do this通常我们会这样做

function Body() {
    static defaultProps = {
        counter: 0
    }
    return (
        <div>
            body
        </div>
    );
}

this obviously doesn't work这显然不起作用

This is usually called a functional component, not a hook component.这通常称为功能组件,而不是钩子组件。

For the defaultProps you can do it like this:对于defaultProps您可以这样做:

const Body = ({ counter }) => {
    return (
        <div>
            {counter}
        </div>
    );
}

Body.defaultProps = {
    counter: 0
}
function Body({counter=0}) {
    return (
        <div>
            body
        </div>
    );
}

counter now has initial value of 0计数器现在的初始值为 0

You can do that simply like this你可以像这样简单地做到这一点

const Body = (props) => {
    const {foo = 'defaultValue'} = props;

    return <div>{foo}</div> // It will show defaultValue if props foo is undefined
}

Hooks are just regular functions, you can define default values the same way as you define them in regular functions钩子只是常规函数,您可以像在常规函数中定义它们一样定义默认值

function useNameHook(initialName = "Asaf") {
  const [name, setName] = useState(initialName);

  // you can return here whatever you want, just the name,
  // just the setter or both
  return name;
}

function Comp({ name }) {
  const myName = useNameHook(name);

  return <h1>Hello {myName}</h1>;
}

function App() {
  return (
    <div className="App">
      {/* without name prop */}
      <Comp />
      {/* with name prop */}
      <Comp name="angry kiwi" />
    </div>
  );
}

You can declare defaultProps outside the functional component.您可以在功能组件之外声明 defaultProps。 In your case it would be something like this -在你的情况下,它会是这样的 -

   function Body(props) {
    return (
        <div>
            {props.counter}
        </div>
    );
  }
  Body.defaultProps = {
      counter: 0
  }

This is for hooks but is not intended for functional components.这适用于钩子,但不适用于功能组件。

const defaultProps = {
  position: "end"
};

const Dropdown = (props) => {
   // The order of arguments is important.
  props = Object.assign({}, defaultProps, props);
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM