简体   繁体   English

将 state 传递到子组件的 prop 中,使用“(this.props.(propHere))”内联访问它,由于“This”而未定义

[英]Passing state down into a prop to child component, accessing it inline with “(this.props.(propHere))” coming up undefined due to “This”

I have a parent component with a state which carries a theme string.我有一个带有主题字符串的 state 的父组件。 (It's just for testing purposes at the moment so don't think too far into the practicality of it please:) ! (目前只是为了测试目的,所以请不要对它的实用性想得太远:)! ) )

Basically, this is the layout thus far.基本上,这是迄今为止的布局。

Parent Component carries state of Theme. Parent Component 带有 Theme 的 state。

Parent passes down current state to child component as "theme" prop using code "theme={this.state.theme}".父级使用代码“theme={this.state.theme}”将当前 state 作为“主题”道具传递给子组件。

Trying to style child element inline with尝试将子元素设置为内联样式

style={{ background: this.props.theme === "light" ? "#fff" : "#000" }}

Getting the error: TypeError: Cannot read property 'props' of undefined .收到错误: TypeError: Cannot read property 'props' of undefined

I know this is because of how "this" is bound.我知道这是因为“this”是如何绑定的。 However, what is the best approach for this?但是,最好的方法是什么?

I want the child element to match the state of the parent component but I need "this" bound correctly.我希望子元素与父组件的 state 匹配,但我需要正确绑定“this”。

It seems that you are using a functional component for the child element which doesn't have this assigned, try changing to似乎您正在为未分配this功能的子元素使用功能组件,请尝试更改为

                     //remove the `this`
style={{ background: props.theme === "light" ? "#fff" : "#000" }}

I know that the question is already answered but heres a tip.我知道这个问题已经回答了,但这里有一个提示。 When you have a function componenent, you can access the prop like this:当您有 function 组件时,您可以像这样访问道具:

someRandomFunc = ({props}) => {

return(
<Text
style={{ background: props.theme === "light" ? "#fff" : "#000" }}>HELLO WORLD</Text>
}
);

If its a Class component.如果它是 Class 组件。 You can directly use this.props :您可以直接使用this.props

class Something extends React.Component{

state = {}

    render(){
return(

<Text style={{ background: this.props.theme === "light" ? "#fff" : "#000" }}></Text>

)
    }
}

Hope this helps in the future!希望这对将来有帮助!

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

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