Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在React样式的组件中使用this.props_Javascript_Reactjs_Styled Components - Fatal编程技术网

Javascript 如何在React样式的组件中使用this.props

Javascript 如何在React样式的组件中使用this.props,javascript,reactjs,styled-components,Javascript,Reactjs,Styled Components,我正在尝试使用道具设计我的组件,如下所示: const MyStyledComponent = styled.div` position: fixed; top: ${this.props.style.top}; left: ${this.props.style.left}; width: ${this.props.style.width}; height: ${this.props.style.height}; `; 但我得到了以下错误: 未捕获的Ty

我正在尝试使用
道具
设计我的组件,如下所示:

const MyStyledComponent = styled.div`
    position: fixed;
    top: ${this.props.style.top};
    left: ${this.props.style.left};
    width: ${this.props.style.width};
    height: ${this.props.style.height};
`;
但我得到了以下错误:

未捕获的TypeError:无法读取未定义的属性“props”


您需要使用一个回调函数,它接受传递给组件的
props
,如下所示:

const MyStyledComponent = styled.div`
  position: fixed;
  top: ${(props) => props.top};
`;

<MyStyledComponent top={5} />;


Dennis,我对react不太熟悉,但是在这种情况下,如果代码不止一次使用
props
,那么让一个需要
props
的函数组件一直编写一个箭头函数不是更好吗?我将用更多的例子详细说明你应该使用解构来获得嵌套的对象值,如果道具不可用,可以使用回退值。
import styled, { createGlobalStyle } from "styled-components";
import { prop } from "styled-tools";

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 5px;
    border: 5px solid pink;
  }
`;

const Box = styled.div`
  height: ${({ height }) => height}px;
  width: ${({ width }) => width}px;
  background-color: ${({ color }) => color};
`;

const Box2 = styled.div`
  ${({ height, width, color }) => ({
    height,
    width,
    "background-color": color
  })}
`;

const Box3 = styled.div`
  height: ${prop("height")}px;
  width: ${prop("width")}px;
  background-color: ${prop("color")};
`;

const N = 100;

const App = () => {
  return (
    <>
      <GlobalStyle />
      <Box width={N} height={N} color="palevioletred" />
      <Box2 width={N * 1.5} height={N * 1.5} color="black" />
      <Box3 width={N * 2} height={N * 2} color="palegoldenrod" />
    </>
  );
};