首页 > 解决方案 > 在反应中调用儿童中的函数?

问题描述

我有一个包含多个Views. 每个View都有一些映射的 child Entities。这些实体中的每一个都有一个关于它是否被折叠/隐藏的状态,称为:this.state.show。每个Entity都有一个切换show状态的按钮。这一切都很好。

我想做的是在View同时显示或隐藏的按钮上添加一个按钮Entities。我认为这很简单,但有几个复杂的因素:

在这里追求的正确策略是什么?我认为“反应”不够吗?

查看.jsx

import React, { Component } from 'react'
import Entity from './Entity.jsx'
import Filter from './Filter.jsx'

class View extends Component {
    render() {
        return (
            <div className="view main">
                {this.props.entities ? this.props.entities.map(
                    (e, i) => (
                        <Entity
                            entity={e}
                            propertyTypes={this.props.propertyTypes}
                            key={i}
                            index={i}
                            taglists={this.props.taglists}
                            ee={this.props.ee}
                        />
                    )
                ) : ""}
            </div>
        )
    }
}

export default View

实体.jsx

import React, { Component } from 'react'
import Property from './Property.jsx'
import Event from './Event.jsx'
import Relationship from './Relationship.jsx'

class Entity extends Component {
    constructor (props) {
        super(props);
        this.state = {
            show: true
        }
        this.showHide = this.showHide.bind(this)
    }

    showHide() {
        this.setState({
            show: !this.state.show
        })
    }

    render() {
        return (
            <div className="entity" id={this.props.entity.name}>
                <div className="entity-header">
                    <h2>
                        <input
                            type="text"
                            value={this.props.entity.name}
                            onChange={this.emit}
                            data-original={this.props.entity.name}
                            data-index={this.props.index}
                            data-event="rename"
                        ></input>
                    </h2>
                    <button
                        className="entity-collapse"
                        data-index={this.props.index}
                        onClick={this.showHide}
                    >{this.state.show ? "-" : "+"}</button>
                </div>
                <div className={this.state.show ? "entity-content" : "entity-content hidden"}>
                    ...
                    removed for clarity
                    ...
                </div>
            </div>
        )
    }
}

export default Entity

标签: javascriptreactjs

解决方案


您的状态应该只在父组件中,而不是任何子组件中。然后,您会将您的函数和状态作为道具传递给孩子们。


推荐阅读