【问题标题】:How to return a variable in jsx and react into a react component如何在 jsx 中返回变量并反应到反应组件中
【发布时间】:2020-06-14 04:31:38
【问题描述】:

我刚开始使用 react icons npm 包为 sanity.io 创建一个图标选择器。我坚持尝试映射一个对象并返回正确的代码以使用Object.values(ReactIcons).map... 做出反应,如果我只是控制台记录其中一个对象值,例如ReactIcons.Fa500Px 我得到以下函数

ƒ (props) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__lib__["a" /* GenIcon */])({"tag":"svg","attr":{"viewBox":"0 0 448 512"},"child":[{"tag":"path","attr":{"d":"M103.3 344.3c-6.5-14.2-6.9-18.3 7.4-…

现在,如果我从 console.log 中获取相同的代码并将其放在 jsx 或 React 组件括号中,例如 <ReactIcons.Fa500Px />,它会很好地呈现图标

但是,如果我尝试在 map 方法中使用类似这样的方法执行此操作,我只会在 dom 中得到一堆元素,看起来像 <x></x>。然而,console.log(x) 返回的一系列函数的格式与我之前刚刚放在括号内的函数格式相同,这导致了一个图标被渲染。

{Object.values(ReactIcons).map(x =>{
    return (
      <>
    {console.log(x)}
    <x/>
    </>
    );
  })}

我最后的尝试是创建一个 Icon 函数并将 props 传递给它并将其呈现为组件。哪个不起作用,但这是尝试。

function Icon(props){
  return(
    <>
      {props.value}
    </>
  )
}

{Object.values(ReactIcons).map(x =>{
 return (
    <>
      {console.log(x)} 
      <Icon value={x}/> 
    </>
   );
 })}

这是整个代码库,只是为了确保我可能将我的 Icon 函数放在错误的位置。

import React from 'react'
import PropTypes from 'prop-types'
import FormField from 'part:@sanity/components/formfields/default'
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event'
import * as ReactIcons from 'react-icons/fa'

console.log(ReactIcons);

const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)))

function Icon(props){
  return(
    <>
      {props.value}
    </>
  )
}


class IconPickerCustom extends React.Component{

    static propTypes = {
        value: PropTypes.string,
        onChange: PropTypes.func.isRequired
    };

    render = () =>{
        const {type, value, onChange} = this.props
        return (
          <>
            <FormField label={type.title} description={type.description}>
              <input
                type="text"
                value={value === undefined ? '' : value}
                onChange={event => onChange(createPatchFrom(event.target.value))}
                ref={element => this._inputElement = element}
              />
            </FormField>
            {Object.values(ReactIcons).map(x =>{
              return (
                <>
              {console.log(x)} // has same result as console log below, except it is all the icons
              <Icon value={x}/> //neithr works
              <x /> //neither works
              </>
              );
            })}
            {console.log(ReactIcons.Fa500Px)}
            <ReactIcons.Fa500Px/>
          </>
        )
    }
}

export default IconPickerCustom;

【问题讨论】:

  • 你有我可以克隆的最小可运行示例吗?我已经在 Codesandbox here 中尝试过,但我无法添加 Sanity 插件代码,因为 import "part:..." 在 Sanity Studio 之外无法工作。
  • 您想要选择下拉菜单中的图标吗?或者只是在 DOM 中作为按钮对齐?
  • 这是一个带有工作健全工作室的仓库,其中的代码在文件github.com/wispyco/sanity-studio-icon 中在文件github.com/wispyco/sanity-studio-icon/blob/master/schemas/…
  • @AWolf 现在只是对齐为按钮,我仍在弄清楚 UI 将如何工作,因为有很多图标,我可能必须实现搜索,但现在我只想输出图标。

标签: javascript reactjs object jsx sanity


【解决方案1】:

我猜你想在对象键中循环

            {Object.keys(ReactIcons).map(x =>{
               let Elm = ReactIcons[x]
              return (
                <Elm /> 
              );
            })}

我只是猜测我不确定

【讨论】:

  • 我尝试了键,但我需要值。谢谢你。
  • 键只是给了我 FaIcon 之类的名字,而值给了我需要进入组件的所有内容
  • Object.keys 像 Fadi 写的那样可以工作,或者使用 Object.values 你可以像 { Object.values(ReactIcons).map((Icon, index) =&gt;{ return &lt;Icon key={index}/&gt;; }) } 这样写
  • @AWolf,它可以与 .values 一起使用,现在它必须是大写的 X 才能将其识别为反应组件。
【解决方案2】:

我得到了理智的帮助,这最终解决了我的问题

import React, { useState } from 'react';
import PropTypes from 'prop-types'
import FormField from 'part:@sanity/components/formfields/default'
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event'
import * as ReactIcons from 'react-icons/fa'

// const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)))

const Icon =({name}) =>{
  const TagName = ReactIcons[name];
  return !!TagName ? <TagName /> : <p>{name}</p>;
}

const Box = ({icon}) =>{
  return(
    <>
        {icon.map((iconsz) => {
            return(
              <>
              <button>
                <Icon name={iconsz}/>
              </button>

              </>
            )
          }     
        )}
    </>
  ) 
}

class IconPickerCustom extends React.Component{

    constructor(props){
      super(props)
      const arr = [];

      Object.keys(ReactIcons).map(go => { 
        arr.push(go);
          this.state = {icon: arr};
        }
      )
      this.handleChange = this.handleChange.bind(this)

    }

    // createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)));

    handleChange = event => {
      const value = event;
      const arr = [];
      Object.keys(ReactIcons).map(go => 
        { 
          if(go.toLowerCase().includes(value)){
            arr.push(go);
          } 
          this.setState({
            icon: arr
          });
        }
      )
    };

    render = () =>{
      const {icon} = this.state

        return (
          <>
            <input
              type="text"
              onChange={event => this.handleChange(event.target.value)}
            />
            <Box icon={icon}/>
          </>
        )
    }
}

export default IconPickerCustom;

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 2020-05-14
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2019-05-31
    • 2018-03-10
    相关资源
    最近更新 更多