简体   繁体   English

在反应组件之间传递道具

[英]pass props between react components

I am trying to learn how to break things down into smaller components and decided to start with the following code from Rows.jsx .我正在尝试学习如何将事物分解为更小的组件,并决定从Rows.jsx中的以下代码开始。 I think my issue is understanding how props is passed between parent/child components.我认为我的问题是了解道具是如何在父/子组件之间传递的。 I've read a number of guides and articles, but I'm confused I'm using import correctly.我已经阅读了许多指南和文章,但我很困惑我是否正确使用了import Or should I be componentizing the handlers?或者我应该对处理程序进行组件化? Please help me understand if I'm doing this right or am I going about this in the wrong way.请帮助我了解我是否正确执行此操作,或者我是否以错误的方式处理此问题。

Rows.jsx ; Rows.jsx ; (previously at the end of DynamicTable.jsx ) (之前在DynamicTable.jsx的末尾)

import React, { Component } from 'react';

function RenderRows () {
    render() {
        var context = this; //modify this for props?
        return  this.state.combatants.map(function(o, i) {
            return (             
                <tr key={"combatant-" + i}>
                    <td>
                        <input
                            id="initiative"
                            type="text"
                            value={o.initiative}
                            onChange={context.handleCombatantChanged.bind(context, i)}
                        />
                    </td>
                    <td>
                        <input
                            id="name"
                            type="text"
                            value={o.name}
                            onChange={context.handleCombatantChanged.bind(context, i)}
                        />
                    </td>                  
                    <td> 
                        <button onClick={context.handleCombatantDeleted.bind(context, i)}> 
                            Delete
                        </button>
                    </td>
                </tr>
            );
        });
    }    
}
export default RenderRows;

DynamicTable.jsx ; DynamicTable.jsx

import React, { Component } from 'react';
import RenderRows from './Rows';

export default class DynamicTable extends Component {
    constructor(props) {
        super(props);

        this.state = {
            initiative: "",
            name: "",
            combatants: []
        }
    }

    updateInitiative(event) {
        this.setState({initiative: event.target.value});
    }
    updateName(event) {
        this.setState({name: event.target.value});
    }

    handleClick() {
        var combatants = this.state.combatants; 
        combatants.push({ //pushing each variable to array
            initiative: this.state.initiative,
            name: this.state.name,
        });

        this.setState({
            combatants: combatants,
            initiative: "",
            name: "",
        });
    }

    handleCombatantChanged(i, event) {
        var combatants = this.state.combatants;
        combatants[i] = event.target.value;
        this.setState({
            combatants: combatants
        });
    }

    handleCombatantDeleted(i) {
        var combatants = this.state.combatants;
        combatants.splice(i, 1);
        this.setState({
            combatants: combatants
        });
    }

    render() {
        return (
            <div>New Combatant
                <table>
                    <td>
                        <th>Initiative</th>
                        <input                    
                            id="initiative"
                            type="text"
                            value={this.state.initiative}
                            onChange={this.updateInitiative.bind(this)}
                        />
                    </td>
                    <td>
                        <th>Name</th>
                        <input
                            id="name"
                            type="text"
                            value={this.state.name}
                            onChange={this.updateName.bind(this)}
                        />
                    </td>
                    <td><th></th>
                        <button onClick={this.handleClick.bind(this)}>
                            Add Combatant
                        </button>
                    </td>
                </table>                
                Current Combatants
                <table className="">
                    <thead>
                        <tr>
                            <th>Initiative</th>
                            <th>Name</th>                          
                            <th>Delete</th> 
                        </tr>
                    </thead>
                    <tbody>                        
                        {this.renderRows()} {/* how to pass this? */}
                    </tbody>
                </table>
                {/* <RenderRows />; didn't work here either */}
            </div>
        );
    }

    //RenderRows (Rows.jsx) used to be here
    renderRows() {
        return <RenderRows />;
    }
}

Passing properties (props) is unidirectional meaning you can only do it in one direction which is down (parent to child), it seems you understand this and want to pass something from your DynamicTable component to your RenderRows component.传递属性(props)是单向的,这意味着您只能在一个向下的方向(父到子)上执行此操作,看来您理解这一点并希望将一些东西从您的DynamicTable组件传递到您的RenderRows组件。

To illustrate how to pass props I'm going to use functional components and I suggest you do so as well but the principle is the same even with class components.为了说明如何传递道具,我将使用功能组件,我建议您也这样做,但即使使用类组件,原理也是一样的。

CodeSandbox 代码沙盒

function DynamicTable() {
  const myRows = [1, 2, 3, 4];
  return <>
      <RenderRows
         rows={myRows} // "myRows" is being passed as the prop "rows"!
      />
  </>;
}

function RenderRows({ rows }) { // destructuring the props makes it easier to identify which props the component expects
  return <>
      {rows.map(row =>
          <div key={row}>I'm row no. {row}</div>
      )}
  </>;
}

You can think of props as the component's "parameters".您可以将 props 视为组件的“参数”。 Note that you cannot pass props upwards from RenderRows to DynamicTable .请注意,您不能将道具从RenderRows向上传递到DynamicTable

Hope this helps, for further reading the new React docs have an excellent tutorial of how to pass props.希望这会有所帮助,为了进一步阅读新的 React 文档,有一个关于如何传递道具的优秀教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM