我做了一個計數應用程序,當您單擊您的級別並獲得金幣時,但如何在另一個組件中使用數據?例如,我想在另一個組件中使用this.state.max。在Reactjs中使用另一個組件中的數據
對不起,我很新的反應
import React, {Component} from 'react';
import '../App.css';
import darkalien from '../assets/darkgray__0000_idle_1.png';
import darkalien2 from '../assets/darkgray__0033_attack_3.png';
import darkalien3 from '../assets/darkgray__0039_fire_5.png';
var style = {
color: 'black',
fontSize: 20
};
var style2 ={
color: '#daa520',
fontSize: 20
}
export default class Home extends Component{
constructor(props) {
super(props);
this.state = {
i: 0,
j: 1,
k: 0,
max: 10,
maxf: 2,
maxi: 10
}
}
onClick(e) {
e.preventDefault();
var level = this.state.j;
this.setState({i: this.state.i + 1});
this.setState({k: this.state.k + 1});
if(this.state.i >= this.state.max){
this.setState({j: this.state.j + 1});
this.setState({i: this.state.i});
this.setState({k: this.state.k});
if(this.state.j === this.state.maxf){
this.setState({maxf: this.state.maxf + 1});
this.setState({max: this.state.max + 10});
}
this.setState({i: this.state.i = 0});
}
}
render(){
return(
<header>
<div className="container" id="maincontent" tabIndex="-1">
<div className="row">
<div className="col-lg-12">
<div className="intro-text">
<p className="name" style={style} id="demo3">Level {this.state.j}</p>
<p className="name" id="demo4" style={style}>Points: {this.state.k}</p>
<p className="name" style={style2} id="demo5">Gold: {this.state.max}</p>
<img id="picture" className="img-responsive" src={darkalien} alt="alien-img" onClick={this.onClick.bind(this)} height="150" width="150"/>
<progress id="demo2" value={this.state.i} max={this.state.max}></progress>
<h1 className="name">Click me!</h1>
<hr className="glyphicon glyphicon-star-empty"></hr>
<span className="skills">Gain Experience ★ Get Coins ★ Purchase Armor</span>
</div>
</div>
</div>
</div>
</header>
);
}
}
我想用this.state.max在我的存儲組件:
import React, {Component} from 'react';
import blaster from '../assets/blaster_1.png';
import blaster2 from '../assets/blaster_3.png';
import alienSuit from '../assets/predatormask__0000_idle_1.png';
import alienHair from
'../assets/alien_predator_mask_0007_hair_profile.png';
import Home from '../components/Home';
export default class Store extends Component{
render(){
return(
<section id="portfolio">
<div className="container">
<div className="row">
<div className="col-lg-12">
<h3>Armor and Weapon Store<span> **Gold:{this.state.j}** </span></h3>
</div>
</div>
<div className="row text-center">
<div className="col-md-3 col-sm-6 hero-feature">
<div className="thumbnail">
<img src={blaster} alt=""/>
<div className="caption">
<h3>Reggae Blaster</h3>
<p>
<a href="#" className="btn btn-primary">Buy Now!</a> <a href="#" className="btn btn-default">More Info</a>
</p>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
傳遞它作爲道具? – Li357