我有一个按钮,需要该按钮才能在单击时更改父状态值。
我知道有很多这样的问题,但我发誓我只是听不懂。
我曾尝试提升状态,但是我做对了
home page button http://prntscr.com/n8jnlh
import React, { Component,Fragment } from 'react'
import App from '../App.css'
import productPage from '../ProductPage'
class NinjaH2R extends Component {
render () {
return (
<Fragment>
<table> {/*lista de produtos */}
<td className="drop">
<div className="dropdown">
<button className="dropbtn">Motos ˅</button>
<div className="dropdown-content">
<div>
<button /*onClick={this.handleClick.bind(this)}*/ >Ninja
400</button>
</div>
</td>
</table>
</Fragment>
)
}
}
export default NinjaH2R
parent state I want to change http://prntscr.com/n8jo07
import React, { Component,Fragment } from 'react'
import Ninja400 from './components/Ninja400'
import product from './productJSON';
import App from './App.css'
import NinjaZX6R from './components/NinjaZX6R';
import Z900 from './components/Z900';
import NinjaH2R from './components/NinjaH2R';
import Toggle from './components/Toggle'
class ProductPage extends Component {
constructor(props){
super(props)
this.state = {
toggle400: false,
toggleZX6R: false,
toggleZ900: false,
toggleH2R: true,
}
let modelo
}
render () {
let modelo=null
if(this.state.toggle400===true){
modelo=<Ninja400 product={product}/>
this.state.toggleZX6R = false
this.state.toggleZ900 = false
this.state.toggleH2R = false
}
if(this.state.toggleZX6R===true){
modelo=<NinjaZX6R product={product}/>
this.state.toggle400 = false
this.state.toggleZ900 = false
this.state.toggleH2R = false
}
if(this.state.toggleZ900===true){
modelo=<Z900 product={product}/>
this.state.toggleZX6R = false
this.state.toggle400 = false
this.state.toggleH2R = false
}
if(this.state.toggleH2R===true){
modelo=<NinjaH2R product={product}/>
this.state.toggleZX6R = false
this.state.toggleZ900 = false
this.state.toggle400 = false
}
console.log(this)
return (
<Fragment >
<div className="ProductPage">
{modelo}
</div>
</Fragment>
)
}
}
export default ProductPage
当我单击NinjaH2R组件上的按钮时,我需要它将位于产品页面组件上的道具“ toggle400”的状态更改为true
答案 0 :(得分:1)
方法是将回调函数定义为从父组件传递到子组件的道具。
当您单击子组件中的按钮时,将执行此回调函数,并且由于它位于父组件中,因此可以调用setState来更改父组件中的状态。
关于如何定义这样的回调确实有很多例子。例如:
在您的代码中,我相信以下方法会起作用:
<NinjaH2R product={product}
callback={this.ninjaHandler}
product={product}
/>
ninjaHandler = () => {
this.setState({ toggle400: true });
}
<button onClick={this.props.callBack}>
Ninja 400
</button>