简体   繁体   English

React - Prop在无状态函数中未定义

[英]React - Prop is undefined in stateless function

I am passing props from one stateless function to another, and I get a reference error saying the prop is undefined. 我将道具从一个无状态函数传递给另一个,我得到一个引用错误,说道具是未定义的。 Here is the parent function: 这是父函数:

const Home = () => {
  return (
    <App>
      <BackgroundImage url="mercedes-car.jpg">
        <h1>Test</h1>
      </BackgroundImage>
    </App>
  )
}

And here is the BackgroundImage function: 这是BackgroundImage函数:

const Image = styled.div`
  background-image: ${props => url(props.imageUrl)};
  background-size: cover;
  height: 100%;
  width: 100%;
`;

const BackgroundImage = (props) => {
    console.log(props)
  return (
    <Image imageUrl={ props.url }>
      { props.children }
    </Image>
  )
}

The error is that url is undefined; 错误是url未定义; however, when I console.log(props), I get an object with url and children. 但是,当我在console.log(props)时,我得到一个带有url和children的对象。 Any direction or explanation as to why this error is throwing would be appreciated! 任何方向或解释为什么这个错误投掷将不胜感激!

you have a scope issue. 你有一个范围问题。 change it to: 将其更改为:

const BackgroundImage = (props) => {
  console.log(props)
  const Image = styled.div`
    background-image: url(${props.url});
    background-size: cover;
    height: 100%;
    width: 100%;
  `;

  return (
    <Image>
      { props.children }
    </Image>
  )
}

basically the props are not available to your image, because styled.div is not a normal react component that has props. 基本上道具不适用于您的图像,因为styled.div不是具有道具的普通反应组件。

Another way is to leave your code as is but set the background image from inside the return function:(and remove it from the styled.div) 另一种方法是保持你的代码不变,但是在return函数中设置背景图像:(并从styled.div中删除它)

  return (
    <Image style={{backgroundImage: `url(${props.url})`}}>
      { props.children }
    </Image>
  )
}

I'm guessing you meant 我猜你的意思

background-image: ${props => url(props.imageUrl)};

to be 成为

background-image: url(${props => props.imageUrl});

since the result of that function needs to be a string. 因为该函数的结果需要是一个字符串。 Otherwise you're trying to call a function called url . 否则你试图调用一个名为url的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM