以下是我的代码,用于从Firebase检索数据并在引导轮播中查看数据。我可以在控制台中看到这些值,但无法在其他组件的props中得到它。
class JobOfferSlider extends Component {
componentDidMount = () => {
var ref = fire.database().ref("Employers/Employer1");
ref.orderByKey().on("child_added", (snapshot) => {
this.setState({ slidercontents: snapshot.val()})
console.log(this.state.slidercontents);
console.log(this.state.slidercontents.Title)
});
var empref = fire.database().ref("Employers/");
empref.orderByKey().on("child_added", (snapshot) => {
this.setState({ employers: snapshot.key})
console.log(this.state.employers);
});
}
state ={
slidercontents : [], employers : []
}
然后我在以下jsx文件中使用道具
class Slidercontent extends Component {
componentWillUpdate = ()=>{
console.log(this.props.employers);
}
render() {
return (
<div className="col-sm text-center border rounded shadow p-3 m-3">
<div className="row">
<div className="col-md-3">
<div className="profilepic"></div>
</div>
<div className="col-md-9">
<h6 className="pt-2 float-left">{this.props.employers}</h6>
</div>
</div>
<h5 className="font-weight-bold pt-3 text-left">{this.props.slidercontents.Description}</h5>
<h5 className="font-weight-bold pt-3 text-left ">{this.props.slidercontents.RatePerHour}</h5>
<div className="row pt-3">
<div className="col-md-2">
<div><i class="fas fa-map-marker-alt"></i></div>
</div>
<div className="col-md-5">
<p className="float-left">{this.props.slidercontents}</p>
</div>
<div className="col-md-5">
<p className="float-right">5 mins ago</p>
</div>
</div>
</div>
);
}
}
但是道具仍然不确定。...如何访问状态值有帮助吗?
答案 0 :(得分:0)
将父组件的状态作为prop传递给子组件(在render函数中):
render() {
return <Slidercontent employers={this.state.employers}
}
通过这种方式,您可以通过以下方式访问子组件中的employers
:
{this.props.employers}