如何将 React 组件的 props 传递给样式化组件 [英] How to pass props of React component to styled component
本文介绍了如何将 React 组件的 props 传递给样式化组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据它所在的 React 组件的 props
设置样式组件的高度.
I am trying set the height of a styled component based on the props
of the React component it is in.
我尝试了以下方法:
const Styled = styled.div`
height: ${props => props.height}
`
class Parent extends React.Component {
render() {
return (
<Styled height={this.props.height}/>
)
}
}
但不知何故它不起作用.有人可以帮我吗?我正在尝试做的事情的最佳做法是什么?
But somehow it doesn't work. Can somebody help me out? What is the best practice for what I am trying to do?
推荐答案
你的语法工作得很好.我怀疑问题出在 height
的值上.我怀疑它不起作用,因为您指定的是像 200
这样的整数,而不是像 200px
这样的有效 CSS 高度字符串.
The syntax you have works just fine. I suspect the problem is the value of height
. I suspect it isn't working because you are specifying an integer like 200
rather than a valid CSS height string like 200px
.
这是一个简单的例子:
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Styled = styled.div`
height: ${props => props.height};
background-color: blue;
color: white;
`;
function App() {
return (
<Styled className="App" height="200px">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</Styled>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这篇关于如何将 React 组件的 props 传递给样式化组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文