[英](REACT.JS)How to increment a data in my component
class Personne extends React.Component {
// constructor(props){
// super(props);
// }
birthdayHandler = () => {
let Age = this.props.age;
let ageToNumber = parseInt(Age);
}
render(){
return(
<Fragment>
<div className={classes.maintitle}>
<h1 style={Name}> {this.props.name}</h1>
<div> Job : {this.props.job}</div>
<AgePersonne age={this.props.age}/>
<div> Sexe : <strong style={sex}>{this.props.sexe ? "Homme" : "Femme"}</strong></div>
<button onClick={(event) => this.birthdayHandler(event)} style={Button}>Birthday</button>
</div>
</Fragment>
)
}
}
我想通过点击按钮来增加这个人的年龄。
AgePersonne 组件看起来像这样:
const agePersonne = (props) => {
const now = new Date();
const year = now.getFullYear();
return(
<div>Age : {props.age} - année de naissance :{year - props.age -1}</div>
)
};`
我已经在带有按钮的父组件中完成了它,但它增加了我所有人的年龄。 APP 组件如下所示:
class 应用扩展组件 {
state = {
personne: [
{name: "Andy GARCIA", age: "28", job:"Web Dev", sexe: true},
{name: "Sylvie MOISAN", age: "60", job:"nurse", sexe: false},
{name: "Benjamin BARIOHAY", age: "27", job:"Web Dev", sexe: true},
{name: "Galina RAZLIVANOVA", age: "29", job:"Web Security consultant", sexe: false},
{name: "Maxime GIRARDEAU", age: "28", job:"Sailer", sexe: true},
]
}
render() {
return (
<Fragment>
<Horloge />
<Personne {...this.state.personne[0]}/>
<Personne {...this.state.personne[1]}/>
<Personne {...this.state.personne[2]}/>
<Personne {...this.state.personne[3]}/>
<Personne {...this.state.personne[4]}/>
</Fragment>
)
}
}
请问你能帮帮我吗? 我真的迷路了,谢谢
您需要在您的App
中创建一个 function 以正确编辑 state,例如:
const editAge = (index, newAge) => {
const newState = Object.assign({}, this.State);
newState[index] = {...newState[index], age: newAge};
this.SetState(newState);
}
并将其传递给您的Personne
组件及其索引:
<Personne editAge={editAge} index={index} (... your other props) />
您将能够按以下方式调用 function: this.props.editAge('29', 0);
这会将 29 设置为App
state 的第一个元素的年龄。
editAge
function 也可以只接受一个personne
object 和索引。 您必须将整个 object 作为 props 传递,如您所愿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.