简体   繁体   English

React:将 html 属性作为 props 传递的最佳方式

[英]React: The best way to pass html attributes as props

For instance, I want to behave a Button as a normal button and enhance the component.例如,我想将 Button 用作普通按钮并增强组件。

<Button type="submit" className="btn">Click me!</Button>

leads to an html element:导致一个 html 元素:

<button type="submit" className="btn">Click me!</button>

Is there a way to write the Button component like this?:有没有办法像这样编写 Button 组件?:

const Button = ({children, ...htmlAttributesOnly}) => (
    <button {...htmlAttributesOnly}>{children}</button>
)

The idea behind is to make a component as flexible as possible by giving access to all of its html elements' attributes.背后的想法是通过访问其所有 html 元素的属性来使组件尽可能灵活。 Or do I have to repeat every html element attribute?还是我必须重复每个 html 元素属性?

You can create a Button component like this.您可以像这样创建一个 Button 组件。

export default function Button(props) {
  return <button {...props}>{props.children}</button>;
}

Later you can use it like this.以后你可以像这样使用它。

  <Button onClick={()=>alert("hello")} style={{padding:10,border:'none',backgroundColor:'white'}} >Click Me</Button>

You were really close to an answer, just wrap your props in curly braces:你真的很接近答案了,只需将你的道具用花括号括起来:

class Button = ({ children, ...rest }) => (
    <button {...rest}>{children}</button>
)

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

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