為了避免僅為傳遞一些props來渲染組件或元素而使用不必要的wrapper, 可以使用 .attrs constructor. 通過它可以添加額外的 props 或 attributes 到組件.
舉例來說,可以通過這種方式給元素添加靜態(tài) props,或者傳遞第三方 prop 給組件(比如傳遞activeClassName給 React Router 的 Link). 此外也可以將dynamic props 添加到組件. .attrs 對(duì)象也接收函數(shù),返回值也將合并進(jìn) props.
示例如下:
const Input = styled.input.attrs({ // static props type: "password", // dynamic props margin: props => props.size || "1em", padding: props => props.size || "1em" })` color: palevioletred; font-size: 1em; border: 2px solid palevioletred; border-radius: 3px; /* dynamically computed props */ margin: ${props => props.margin}; padding: ${props => props.padding}; `; render( <div> <Input placeholder="A small text input" size="1em" /> <br /> <Input placeholder="A bigger text input" size="2em" /> </div> );
正如所見,我們可以在插值中訪問新創(chuàng)建的 props,type attribute也正確的傳遞給了元素.
更多建議: