盖茨比中对象内部的道具
Props inside object in Gatsby
我正在尝试创建一个以边距值作为道具的对象。然后我将 div 的样式设置为同一个对象,然后采用边距。
import React from 'react'
import Link from 'gatsby-link'
import { styles } from '../styles.js'
const margins = {
marginTop: this.props.top,
marginBottom: this.props.bot
}
const Header = ({ siteTitle }, props) => (
<div style={margins}>
<h1> Content </h1>
</div>
)
export default Header
但它不起作用。我怎样才能让道具发挥作用?
谢谢
margins
是一个简单的对象。
可能有多种解决方法,但我建议您查看 styled-components
(参考 Adapting based on props)以了解此类情况。
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Content = styled.div`
margin-top: ${props => props.top};
margin-bottom: ${props => props.bot};
`;
const Header = ({ siteTitle }, props) => (
// <div style={margins}>
// <h1> Content </h1>
// </div>
<Content top={"100px"} bottom={"500px"}>
Some Content!
</Content>
);
function App() {
return (
<div className="App">
<Header />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您可以找到我在 gatsby 网站上使用 styled-components
的一些示例。
https://github.com/dance2die/landingpage/blob/master/src/components/Emojis.js#L8
声明了一个表情符号组件,
const Emoji = styled.img.attrs({
src: props => props.src,
alt: props => props.alt,
})`
height: 3rem;
margin-right: 2rem;
`
通过传递 src
& alt
描述来使用。
const CreationsEmoji = () => (
<Emoji src={creationsEmoji} alt="Creations Emoji" />
)
我正在尝试创建一个以边距值作为道具的对象。然后我将 div 的样式设置为同一个对象,然后采用边距。
import React from 'react'
import Link from 'gatsby-link'
import { styles } from '../styles.js'
const margins = {
marginTop: this.props.top,
marginBottom: this.props.bot
}
const Header = ({ siteTitle }, props) => (
<div style={margins}>
<h1> Content </h1>
</div>
)
export default Header
但它不起作用。我怎样才能让道具发挥作用?
谢谢
margins
是一个简单的对象。
可能有多种解决方法,但我建议您查看 styled-components
(参考 Adapting based on props)以了解此类情况。
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Content = styled.div`
margin-top: ${props => props.top};
margin-bottom: ${props => props.bot};
`;
const Header = ({ siteTitle }, props) => (
// <div style={margins}>
// <h1> Content </h1>
// </div>
<Content top={"100px"} bottom={"500px"}>
Some Content!
</Content>
);
function App() {
return (
<div className="App">
<Header />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您可以找到我在 gatsby 网站上使用 styled-components
的一些示例。
https://github.com/dance2die/landingpage/blob/master/src/components/Emojis.js#L8
声明了一个表情符号组件,
const Emoji = styled.img.attrs({
src: props => props.src,
alt: props => props.alt,
})`
height: 3rem;
margin-right: 2rem;
`
通过传递 src
& alt
描述来使用。
const CreationsEmoji = () => (
<Emoji src={creationsEmoji} alt="Creations Emoji" />
)