包装Fabric组件时合并样式的最佳方法是什么?

时间:2020-03-01 03:48:49

标签: reactjs typescript office-ui-fabric

考虑一下,我正在包装一个Fabric组件,在其中应用了一些样式,并希望合并其props中传递的任何样式。 我能想到的最好的是:

const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fabric;

const MyTextField = (props: IButtonProps) => {
  const  { styles, ...otherProps } = props;

  const myStyles = stylesProps => {
    // props.styles can be a function, an object or undefined
    const stylesAsObject = typeof (styles) === "function" ? styles(stylesProps) : styles;
    return mergeStyleSets({ root: { maxWidth: 250 }, field: { backgroundColor: "pink"}}, stylesAsObject);
  };

  return <TextField styles={myStyles} {...otherProps} />;
}

const TextFieldExample () => (<MyTextField readOnly value="My text field" styles={{field: { fontWeight: 600}}} />
  );

ReactDOM.render(<Fabric><TextFieldExample /></Fabric>, document.getElementById('content'));

This works,但有点冗长。

是否有某些版本的mergeStylesets可以写:

const myStyles = mergeStylesets({ root: { maxWidth: 250 }, field: { backgroundColor: "pink"}}, props.styles);

1 个答案:

答案 0 :(得分:0)

我发现了concatStyleSetsWithProps

const { TextField, Fabric , IButtonProps, concatStyleSetsWithProps } = window.Fabric;

const MyTextField = (props: IButtonProps) => {
  return <TextField  {...props} styles={stylesProps => concatStyleSetsWithProps(props, { root: { maxWidth: 250 }, field: { backgroundColor: "pink"}}, props.styles)} />;
}

const TextFieldExample= () => (<MyTextField readOnly value="My text field" styles={{field: { fontWeight: 600}}} />);

const ExampleWrapper = () => <Fabric><TextFieldExample /></Fabric>;
ReactDOM.render(<ExampleWrapper />, document.getElementById('content'))

https://codepen.io/onlyann/pen/yLNXvPd?editors=1111