。
由于道具是不可变的,我不能简单地在组件1中保存它的状态并转发它,对吗?是的,我读过有关redux的内容,但不想使用它。我希望有可能解决它 应对 </跨度> 。我错了吗? 鈥
我发现以下工作解决方案将onClick函数参数从child传递给父组件:
的 传递方法的版本() </强>
//ChildB componentclass ChildB extends React.Component {render() { var handleToUpdate = this.props.handleToUpdate; return (<div><button onClick={() => handleToUpdate('someVar')}> Push me </button> </div>)}}//ParentA componentclass ParentA extends React.Component {constructor(props) { super(props); var handleToUpdate = this.handleToUpdate.bind(this); var arg1 = '';}handleToUpdate(someArg){ alert('We pass argument from Child to Parent: ' + someArg); this.setState({arg1:someArg});}render() { var handleToUpdate = this.handleToUpdate; return (<div> <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)}}if(document.querySelector(“#demo”)){ ReactDOM.render( , document.querySelector(“#demo”) );}</code>
//ChildB componentclass ChildB extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (<div><button onClick={() => handleToUpdate('someVar')}>
Push me
</button>
</div>)
}
//ParentA componentclass ParentA extends React.Component {
constructor(props) {
super(props);
var handleToUpdate = this.handleToUpdate.bind(this);
var arg1 = '';
handleToUpdate(someArg){
alert('We pass argument from Child to Parent: ' + someArg);
this.setState({arg1:someArg});
var handleToUpdate = this.handleToUpdate;
return (<div>
<ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
if(document.querySelector(“#demo”)){ ReactDOM.render( , document.querySelector(“#demo”) );}
</code>
看看JSFIDDLE 的 传递箭头功能的版本 </强> //ChildB componentclass ChildB extends React.Component {render() { var handleToUpdate = this.props.handleToUpdate; return (<div> <button onClick={() => handleToUpdate('someVar')}> Push me </button> </div>)}}//ParentA componentclass ParentA extends React.Component { constructor(props) { super(props); }handleToUpdate = (someArg) => { alert('We pass argument from Child to Parent: ' + someArg);}render() { return (<div> <ChildB handleToUpdate = {this.handleToUpdate} /></div>)}}if(document.querySelector(“#demo”)){ ReactDOM.render( , document.querySelector(“#demo”) );}</code> 看看JSFIDDLE
看看JSFIDDLE
的 传递箭头功能的版本 </强>
//ChildB componentclass ChildB extends React.Component {render() { var handleToUpdate = this.props.handleToUpdate; return (<div> <button onClick={() => handleToUpdate('someVar')}> Push me </button> </div>)}}//ParentA componentclass ParentA extends React.Component { constructor(props) { super(props); }handleToUpdate = (someArg) => { alert('We pass argument from Child to Parent: ' + someArg);}render() { return (<div> <ChildB handleToUpdate = {this.handleToUpdate} /></div>)}}if(document.querySelector(“#demo”)){ ReactDOM.render( , document.querySelector(“#demo”) );}</code>
<button onClick={() => handleToUpdate('someVar')}>
//ParentA componentclass ParentA extends React.Component { constructor(props) { super(props); }
handleToUpdate = (someArg) => {
<ChildB handleToUpdate = {this.handleToUpdate} /></div>)
我喜欢传递函数的答案,这是一种非常方便的技巧。
另一方面,您也可以使用pub / sub或使用变体,调度程序来实现此目的 助焊剂 确实。理论超级简单,有组件5发送组件3正在监听的消息。组件3然后更新其触发重新渲染的状态。这需要有状态的组件,这取决于您的观点,可能是也可能不是反模式。我个人反对他们,并且宁愿其他东西正在监听调度和更改状态从上到下(Redux这样做,但增加了额外的术语)。
import { Dispatcher } from fluximport { Component } from Reactconst dispatcher = new Dispatcher()// Component 3// Some methods, such as constructor, omitted for brevityclass StatefulParent extends Component { state = { text: ‘foo’ } componentDidMount() { dispatcher.register( dispatch => { if ( dispatch.type === ‘change’ ) { this.setState({ text: ‘bar’ }) } } } render() { return { this.state.text } }}// Click handlerconst onClick = event => { dispatcher.dispatch({ type: ‘change’ })}// Component 5 in your exampleconst StatelessChild = props => { return Click me}</code>
import { Dispatcher } from fluximport { Component } from React
const dispatcher = new Dispatcher()
// Component 3// Some methods, such as constructor, omitted for brevityclass StatefulParent extends Component { state = { text: ‘foo’ }
componentDidMount() { dispatcher.register( dispatch => { if ( dispatch.type === ‘change’ ) { this.setState({ text: ‘bar’ }) } } }
render() { return { this.state.text } }}
render() { return
// Click handlerconst onClick = event => { dispatcher.dispatch({ type: ‘change’ })}
// Component 5 in your exampleconst StatelessChild = props => { return Click me}
与Flux捆绑的调度程序非常简单,只需注册回调并在发生任何调度时调用它们,通过调度上的内容(在上面的简洁示例中没有) payload 与发送,只是一个消息ID)。如果对您更有意义,您可以非常轻松地将其调整为传统的pub / sub(例如,使用事件中的EventEmitter或其他版本)。
payload
我找到了以下工作解决方案,通过param将onClick函数参数从child传递给父组件:
父类:
class Parent extends React.Component {constructor(props) { super(props)// Bind the this context to the handler functionthis.handler = this.handler.bind(this);// Set some statethis.state = { messageShown: false};}// This method will be sent to the child componenthandler(param1) {console.log(param1); this.setState({ messageShown: true });}// Render the child component and set the action property with the handler as valuerender() { return }}</code>
class Parent extends React.Component {constructor(props) { super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
messageShown: false
};
// This method will be sent to the child componenthandler(param1) {console.log(param1); this.setState({ messageShown: true });}
// Render the child component and set the action property with the handler as valuerender() { return }}
儿童班: class Child extends React.Component {render() { return ( {/ The button will execute the handler function set by the parent component /} )} }</code>
儿童班:
class Child extends React.Component {render() { return ( {/ The button will execute the handler function set by the parent component /} )} }</code>
class Child extends React.Component {render() { return ( {/ The button will execute the handler function set by the parent component /} )} }
当你需要在任何级别的孩子与父母之间进行交流时,最好是利用它 的 上下文 </强> 。在父组件中定义子项可以调用的上下文,例如
在案例组件3中的父组件中
static childContextTypes = { parentMethod: React.PropTypes.func.isRequired }; getChildContext() { return { parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child) }; }parentMethod(parameter_from_child){// update the state with parameter_from_child}</code>
static childContextTypes = { parentMethod: React.PropTypes.func.isRequired };
getChildContext() {
return {
parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
parentMethod(parameter_from_child){// update the state with parameter_from_child}
现在在子组件(在您的情况下为组件5),只需告诉它 要使用其父级上下文的组件。 static contextTypes = { parentMethod: React.PropTypes.func.isRequired };render(){ return( this.context.parentMethod(new_state_value)} underlayColor=’gray’ > <Text> update state in parent component </Text> </TouchableHighlight>)}</code> 你可以找到Demo项目 回购
现在在子组件(在您的情况下为组件5),只需告诉它 要使用其父级上下文的组件。
static contextTypes = { parentMethod: React.PropTypes.func.isRequired };render(){ return( this.context.parentMethod(new_state_value)} underlayColor=’gray’ > <Text> update state in parent component </Text> </TouchableHighlight>)}</code>
static contextTypes = { parentMethod: React.PropTypes.func.isRequired };render(){ return( this.context.parentMethod(new_state_value)} underlayColor=’gray’ >
<Text> update state in parent component </Text>
</TouchableHighlight>
)}
你可以找到Demo项目 回购
我想感谢最热烈的回答,让我了解自己的问题基本上是箭头函数的变化和从子组件传递param:
class Parent extends React.Component { constructor(props) { super(props) // without bind, replaced by arrow func below } handler = (val) => { this.setState({ someVar: val }) } render() { return }}class Child extends React.Component { render() { return this.props.handler(‘the passing value’)}/ > }}</code>
class Parent extends React.Component { constructor(props) { super(props) // without bind, replaced by arrow func below }
handler = (val) => { this.setState({ someVar: val }) }
render() { return }}
class Child extends React.Component { render() { return this.props.handler(‘the passing value’)}/ > }}
希望它可以帮助某人。
- 我们可以创建ParentComponent并使用handleInputChange方法来更新ParentComponent状态。导入ChildComponent,我们将两个道具从父组件传递给子组件ie.handleInputChange函数和计数。
import React, { Component } from ‘react’;import ChildComponent from ‘./ChildComponent’;class ParentComponent extends Component { constructor(props) { super(props); this.handleInputChange = this.handleInputChange.bind(this); this.state = { count: ‘’, }; } handleInputChange(e) { const { value, name } = e.target; this.setState({ [name]: value }); } render() { const { count } = this.state; return ( ); }}</code>
import React, { Component } from ‘react’;import ChildComponent from ‘./ChildComponent’;
class ParentComponent extends Component { constructor(props) { super(props); this.handleInputChange = this.handleInputChange.bind(this); this.state = { count: ‘’, }; }
handleInputChange(e) { const { value, name } = e.target; this.setState({ [name]: value }); }
render() { const { count } = this.state; return ( ); }}
现在我们创建ChildComponent文件并保存为ChildComponent.jsx。此组件是无状态的,因为子组件没有状态。我们使用prop-types库进行道具类型检查。 import React from ‘react’;import { func, number } from ‘prop-types’;const ChildComponent = ({ handleInputChange, count }) => ( );ChildComponent.propTypes = { count: number, handleInputChange: func.isRequired,};ChildComponent.defaultProps = { count: 0,};export default ChildComponent; </code> </pre></LI>
现在我们创建ChildComponent文件并保存为ChildComponent.jsx。此组件是无状态的,因为子组件没有状态。我们使用prop-types库进行道具类型检查。
import React from ‘react’;import { func, number } from ‘prop-types’;const ChildComponent = ({ handleInputChange, count }) => ( );ChildComponent.propTypes = { count: number, handleInputChange: func.isRequired,};ChildComponent.defaultProps = { count: 0,};export default ChildComponent; </code> </pre></LI>
import React from ‘react’;import { func, number } from ‘prop-types’;
const ChildComponent = ({ handleInputChange, count }) => ( );
ChildComponent.propTypes = { count: number, handleInputChange: func.isRequired,};
ChildComponent.defaultProps = { count: 0,};
export default ChildComponent;
</pre>
</LI>