gpt4 book ai didi

javascript - Gatsby 中对象内部的 Prop

转载 作者:行者123 更新时间:2023-12-03 01:23:50 25 4
gpt4 key购买 nike

我正在尝试创建一个以边距值作为 Prop 的对象。然后我将 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

但是它不起作用。我怎样才能让 Prop 发挥作用?

谢谢

最佳答案

margins 是一个简单的对象。
可能有多种解决方法,但我建议您针对这种情况查看 styled-components (请参阅 Adapting based on props )。

工作演示。
Edit moo9vppx4x

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;
`

通过传递 srcalt 描述来使用。

const CreationsEmoji = () => (
<Emoji src={creationsEmoji} alt="Creations Emoji" />
)

关于javascript - Gatsby 中对象内部的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com