Reactjs 我想使用道具将计数器值传递给我的组件
我想使用道具将计数器值传递给我的组件。我不知道该如何传递计数器值。这是我的组件计数器Reactjs 我想使用道具将计数器值传递给我的组件,reactjs,Reactjs,我想使用道具将计数器值传递给我的组件。我不知道该如何传递计数器值。这是我的组件计数器 import React, { Component } from 'react' class Counter extends Component { constructor(props) { super(props) this.state = { count: 0 } } increment(props) {
import React, { Component } from 'react'
class Counter extends Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
increment(props) {
this.setState((prevState) => ({
count: prevState.count + 1
}))
console.log(this.state.count)
}
incrementFive() {
this.increment()
this.increment()
this.increment()
this.increment()
this.increment()
}
render() {
return (
<div>
<div> Count - {this.state.count}</div>
<button onClick={() => this.incrementFive()}>Increment</button>
</div>
)
}
}
export default Counter
import React,{Component}来自“React”
类计数器扩展组件{
建造师(道具){
超级(道具)
此.state={
计数:0
}
}
增量(道具){
this.setState((prevState)=>({
计数:prevState.count+1
}))
console.log(this.state.count)
}
递增五(){
这个。增量()
这个。增量()
这个。增量()
这个。增量()
这个。增量()
}
render(){
返回(
Count-{this.state.Count}
this.incrementFive()}>Increment
)
}
}
导出默认计数器
我在App.js中使用了计数器组件,如下所示
<Counter></Counter>
您应该遵循此示例。请检查一下
import React, {Component} from 'react'
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
increment(props) {
this.setState((prevState, props) => ({
count: prevState.count + props.incrementBy
}));
console.log(this.state.count)
}
render() {
return (
<div>
<div> Count - {this.state.count}</div>
<button onClick={() => this.increment()}>Increment</button>
</div>
)
}
}
export default Counter;
import React,{Component}来自“React”
类计数器扩展组件{
建造师(道具){
超级(道具);
此.state={
计数:0
}
}
增量(道具){
this.setState((prevState,props)=>({
计数:prevState.count+props.incrementBy
}));
console.log(this.state.count)
}
render(){
返回(
Count-{this.state.Count}
this.increment()}>increment
)
}
}
导出默认计数器;
在App.js中,您应该写:
<Counter incrementBy={5}/>
这几乎是react
setState
中使用功能更新的示例之一。仅供参考,setState
之后的console.log将始终显示处理更新之前的计数值。