【问题标题】:Not rendering JSX from function in React不从 React 中的函数渲染 JSX
【发布时间】:2019-09-08 20:45:06
【问题描述】:

该函数将按钮单击的值作为道具。映射数据以将该按钮值与数据 JSON 中称为“类”的键进行比较。我正在正确获取所有数据。我所有的 console.logs 都返回正确的值。但是由于某种原因,我无法渲染任何东西。

我尝试添加两个返回语句。它甚至没有用“TEST”这个词来渲染 p 标签。我错过了什么吗?我已经包含了一个代码沙箱:https://codesandbox.io/s/react-example-8xxih

例如,当我单击“数学”按钮时,我想将教数学的两位老师显示为按钮下方的两个气泡。 所有数据正在加载。只是渲染有问题。

function ShowBubbles(props){
    console.log('VALUE', props.target.value)
   return (
       <div id='bubbles-container'>
          <p>TEST</p> 
       {Data.map((item,index) =>{
        if(props.target.value == (Data[index].classes)){
          return (
               <Bubble key={index} nodeName={Data[index].name}>{Data[index].name}
              </Bubble>    
          )

        }
    })}
    </div>
   )
}

【问题讨论】:

  • 您能否将整个代码分享到沙盒或类似的东西中,以便轻松重现问题以进行调试。
  • 您能展示一下您是如何渲染ShowBubbles 组件的吗?与您的渲染问题无关,但如果您尝试仅渲染一个Bubble(满足条件props.target.value == (Data[index].classes 的那个),您应该在第一个return 之前过滤您的Data
  • @rakesh-ranjan 我已经包含了一个 CodeSandbox。例如,我想在单击“数学”按钮时显示教授该课程的两位老师的姓名,并将其显示为下面的气泡。 codesandbox.io/s/react-example-8xxih
  • @mgarcia 我想将那些符合条件的渲染为气泡。我在我的渲染中注释掉了 ShowBubbles 组件。它被设置为三元组。但它不起作用。

标签: javascript reactjs jsx


【解决方案1】:

沙盒链接:https://codesandbox.io/embed/react-example-m1880

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
const circleStyle = {
  width: 100,
  height: 100,
  borderRadius: 50,
  fontSize: 30,
  color: "blue"
};

const Data = [
  {
    classes: ["Math"],
    name: "Mr.Rockow",
    id: "135"
  },
  {
    classes: ["English"],
    name: "Mrs.Nicastro",
    id: "358"
  },
  {
    classes: ["Chemistry"],
    name: "Mr.Bloomberg",
    id: "405"
  },
  {
    classes: ["Math"],
    name: "Mr.Jennings",
    id: "293"
  }
];

const Bubble = item => {
  let {name} = item.children.singleItem;
  return (
    <div style={circleStyle} onClick={()=>{console.log(name)}}>
      <p>{item.children.singleItem.name}</p>
    </div>
  );
};

function ShowBubbles(props) {
  var final = [];
  Data.map((item, index) => {
    if (props.target.value == Data[index].classes) {
      final.push(Data[index])
    }
  })
  return final;
}

function DisplayBubbles(singleItem) {
  return <Bubble>{singleItem}</Bubble>
}

class Sidebar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      json: [],
      classesArray: [],
      displayBubble: true
    };
    this.showNode = this.showNode.bind(this);
  }

  componentDidMount() {
    const newArray = [];
    Data.map((item, index) => {
      let classPlaceholder = Data[index].classes.toString();
      if (newArray.indexOf(classPlaceholder) == -1) {
        newArray.push(classPlaceholder);
      }
      // console.log('newArray', newArray)
    });
    this.setState({
      json: Data,
      classesArray: newArray
    });
  }

  showNode(props) {
    this.setState({
      displayBubble: true
    });

    if (this.state.displayBubble === true) {
      var output = ShowBubbles(props);
      this.setState({output})
    }
  }
  render() {
    return (
      <div>
        {/* {this.state.displayBubble ? <ShowBubbles/> : ''}  */}

        <div id="sidebar-container">
          <h1 className="sidebar-title">Classes At School</h1>

          <h3>Classes To Search</h3>

          {this.state.classesArray.map((item, index) => {
            return (
              <button
                onClick={this.showNode}
                className="btn-sidebar"
                key={index}
                value={this.state.classesArray[index]}
              >
                {this.state.classesArray[index]}
              </button>
            );
          })}
        </div>
        {this.state.output && this.state.output.map(item=><DisplayBubbles singleItem={item}/>)}
      </div>
    );
  }
}

ReactDOM.render(<Sidebar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 这很好用,Dhaval!感谢您花时间提供代码解决方案!
  • 代码还需要重构,我匆忙完成了。但好处是它有效。 :)
  • 是的,再次感谢您,Dhaval!如果您有时间,请在沙箱中向我展示您将如何重构以更好地安排 React 代码。非常感谢!
  • 有机会我一定会的。
  • Dhaval,如何为显示的每个气泡添加 onclick?我希望单击事件对 Data 数组执行其他操作。
【解决方案2】:

这里的问题是 ShowBubbles 没有被渲染到 DOM 中,而是(根据沙箱),ShowBubbles(一个 React 组件)在 onClick 按钮处理程序中被直接调用。虽然您在技术上可以做到这一点,但从函数调用组件将导致 JSX,本质上,您需要手动将其插入 DOM。

采用这种方法不是很 React-y,通常有一种更简单的方法来解决这个问题。一种这样的方法是直接从另一个 React 组件调用 ShowBubbles,例如在你的按钮之后使用类似的东西:

<ShowBubbles property1={prop1Value} <etc...> />

您需要解决代码(至少来自沙盒)的其他一些问题,但这至少可以帮助您朝着正确的方向前进。

【讨论】:

  • 感谢您抽出宝贵时间查看沙盒。您能否提供一些具体的工作示例,说明如何在沙盒中重新排列代码?
猜你喜欢
  • 2017-03-10
  • 2021-10-11
  • 2019-01-18
  • 2021-12-09
  • 2020-06-18
  • 2020-06-28
  • 2018-12-29
  • 2017-10-12
  • 1970-01-01
相关资源
最近更新 更多