我使用两个组件在 React 中编写了一些虚拟代码。
第一个:
import React, { Component } from "react";
import Square from "./components/square";
import "./App.css";
class App extends Component {
render() {
return (
<div>
<Square color={this.props.CardStyle} />
</div>
);
}
}
export default App;
第二个:
import React, { Component } from "react";
class Square extends Component {
render() {
var CardStyle = {
height: "200px",
width: "150px",
padding: 0,
backgroundColor: "#FFF",
filter: "drop-shadow(0px 0px 5px #666)"
};
const mera = "merone";
return (
<div style={CardStyle}>
<p>{this.props.mera}</p>
</div>
);
}
}
export default Square;
现在,我想在 Square 组件的 p 上渲染它的 Prop “mera”,但它没有。另外,我想渲染将其传递给父组件 App。我该怎么做?
最佳答案
我相信你的困惑在于如何使用 react Prop 。 ( Props and components ) React 中的 Prop 只是一个从父级传递给子级的变量。在这种情况下,您正在寻找子组件“Square”中的 Prop “mera”,但您并未将其从父级传递下来。如果你想从你的子组件中设置值,你应该使用 react 状态。否则,您将使用以下方式传递它:
<Square mera={"merone"} color={this.props.CardStyle} />
在 React 中有多种使用变量的方法。
Props(确保传递变量):
import React, { Component } from "react";
class Square extends Component {
render() {
var CardStyle = {
height: "200px",
width: "150px",
padding: 0,
backgroundColor: "#FFF",
filter: "drop-shadow(0px 0px 5px #666)"
};
return (
<div style={CardStyle}>
<p>{this.props.mera}</p>
</div>
);
}
}
export default Square;
状态:
import React, { Component } from "react";
class Square extends Component {
state = { mera: "merone" };
render() {
var CardStyle = {
height: "200px",
width: "150px",
padding: 0,
backgroundColor: "#FFF",
filter: "drop-shadow(0px 0px 5px #666)"
};
return (
<div style={CardStyle}>
<p>{this.state.mera}</p>
</div>
);
}
}
export default Square;
作用域变量:
import React, { Component } from "react";
class Square extends Component {
render() {
var CardStyle = {
height: "200px",
width: "150px",
padding: 0,
backgroundColor: "#FFF",
filter: "drop-shadow(0px 0px 5px #666)"
};
const mera = "merone";
return (
<div style={CardStyle}>
<p>{mera}</p>
</div>
);
}
}
export default Square;
类属性(修改后不会重新渲染组件):
import React, { Component } from "react";
class Square extends Component {
mera = "merone";
render() {
var CardStyle = {
height: "200px",
width: "150px",
padding: 0,
backgroundColor: "#FFF",
filter: "drop-shadow(0px 0px 5px #666)"
};
return (
<div style={CardStyle}>
<p>{this.mera}</p>
</div>
);
}
}
export default Square;
关于javascript - react Prop 不在父组件中呈现,甚至在同一个组件中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51274190/