如何在React的父组件中为React子组件设置样式?

时间:2020-03-30 08:34:15

标签: reactjs styled-components

如果我有这样的子组件:

imports ... 

type Props = {
  size: number;
  setSize: (size: SizeState) => void;
};

const Slider: React.FC<Props> = ({size, setSize}) => {

  const slider = useRef(66); // set slider to inital value
  console.log('slider ', slider.current.initialLowValue); // doesn't work: "slider.current.initialLowValue is not a function"

  return (
    <View style={styles.container}>
      <RangeSlider
        ref={slider}
        max={70}
        min={50}
        step={1}
        initialLowValue={size} // I want to have access to this property
        value={size}
        onValueChanged={value => setSize({size: value})}
      />
    </View>
  );
};

function mapStateToProps(state: RootState) {
  return {
    height: state.sizeResult.size,
  };
}

const mapDispatchToProps = {
  setSize,
};

export default connect(mapStateToProps, mapDispatchToProps)(Slider);

然后我要像这样将样式添加到父组件:

const Div = styled.div`
  display: inline-block;
`;
const Div = styled.button`
  display: block;
  background-color: red;
  margin-left: auto;
  margin-right: auto;
`;
export default class Child extends React.Components{
  render(){
    return <Div><Button>Test</Button></Div>;
  }
}

所以我想这是处理错误的方法?还有另一种方法吗?

2 个答案:

答案 0 :(得分:0)

我是新来的,这很明显,但是为什么不直接在父级上使用内联样式呢?

    const parentStyle = {
      margin-top: "10px"
    }
    export default class Parent extends React.Components{
      render(){
        return <Child style={parentStyle}/>;
      }
    }

答案 1 :(得分:0)

答案是将属性className添加到父组件,并将其应用于子类的外部Element。然后这是工作。在样式化组件文档中对此进行了描述:https://styled-components.com/docs/advanced#styling-normal-react-components