programing

배열하는 방법이 있습니다.반작용으로 합류하다

showcode 2023. 3. 6. 21:39
반응형

배열하는 방법이 있습니다.반작용으로 합류하다

array.join과 같은 구문을 사용하여 배열의 각 요소 사이에 구분자를 삽입하고 싶습니다.

예를 들어 다음과 같습니다.

render() {
 let myArray = [1,2,3];
 return (<div>
   {myArray.map(item => <div>{item}</div>).join(<div>|</div>)}
</div>);
}

lodash.transform 접근 방식을 사용하여 작업을 수행했지만, 보기 흉한 느낌이 듭니다..join(<some-jsx>)각 아이템 사이에 구분자를 넣도록 하겠습니다.

를 사용할 수도 있습니다.reduce배열의 모든 요소 사이에 구분 기호를 삽입하려면:

render() {
  let myArray = [1,2,3];
  return (
    <div>
      {
        myArray
          .map(item => <div>{item}</div>)
          .reduce((acc, x) => acc === null ? [x] : [acc, ' | ', x], null)
      }
    </div>
  );
}

또는 fragment를 사용합니다.

render() {
  let myArray = [1,2,3];
  return (
    <div>
      {
        myArray
          .map(item => <div>{item}</div>)
          .reduce((acc, x) => acc === null ? x : <>{acc} | {x}</>, null)
      }
    </div>
  );
}

또, 조합해서 할 수도 있습니다..reduce그리고.React 프래그먼트

function jsxJoin (array, str) {
  return array.length > 0
    ? array.reduce((result, item) => <>{result}{str}{item}</>)
    : null;
}

function jsxJoin (array, str) {
  return array.length > 0
    ? array.reduce((result, item) => <React.Fragment>{result}{str}{item}</React.Fragment>)
    : null;
}

const element = jsxJoin([
  <strong>hello</strong>,
  <em>world</em>
], <span> </span>);

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

React Elements와 .join을 시도해도 잘 되지 않을 것입니다.이렇게 하면 당신이 필요로 하는 결과를 얻을 수 있습니다.

render() {
    let myArray = [1,2,3];
    return (
      <div>
        {myArray.map((item, i, arr) => {
          let divider = i<arr.length-1 && <div>|</div>;
          return (
            <span key={i}>
                <div>{item}</div>
                {divider}
            </span>
          )
        })}
      </div>
    );
  }

사용.Array.map그리고.React.Fragment각 배열 항목을 원하는 JSX 요소와 결합할 수 있습니다.다음 예에서는 다음을 사용하고 있습니다.<br />이 태그는 원하는 요소를 대체할 수 있습니다.

const lines = ['line 1', 'line 2', 'line 3'];
lines.map((l, i) => (
    <React.Fragment key={i}>{l}{i < (lines.length - 1) ? <br /> : ''}</React.Fragment>
));

출력은 다음과 같습니다.

line 1 <br />
line 2 <br />
line 3

참고로 반응하는 기능을 제공할 수도 있습니다.제 접근법은.forEach한 쌍의push(value); push(glue);, 그 후pop()끈적끈적한 접착제...

function() {
    joinLike = [];
    originData.forEach(function(v,i) {
        joinLike.push(v);
        joinLike.push(<br>);
    })
    joinLike.pop();
    return joinLike;
}

요청된 솔루션을 생성하기 위해 React join은 맵 및 축소에서는 작동하지 않는 것 같습니다.

render() {
  let myArray = [1, 2, 3];
  return (
    <div>
        {myArray
            .map(item => <div>{item}</div>)
            .reduce((result, item) => [result, <div>|</div>, item])}
    </div>
  );
}

당신도 시도해 볼 수 있다.flatMap()브라우저 지원이 오고 있지만 그때까지는 폴리필을 사용할 수 있습니다.유일한 단점은 마지막 요소를 잃는다는 것입니다.

예.

{myArray.flatMap(item => [<div>{item}</div>, <div>|</div>]).slice(0, -1)}

또는

{myArray.flatMap((item, i) => [
  <div>{item}</div>,
  i < myArray.length - 1 ? <div>|</div> : null
])

이와 같은 기능을 사용할 수 있습니다.

function componentsJoin(components, separator) {
  return components.reduce(
    (acc, curr) => (acc.length ? [...acc, separator, curr] : [curr]),
    []
  );
}

또는 패키지를 사용할 수 있습니다.이 패키지는 https://www.npmjs.com/package/react-join에서 찾을 수 있습니다.

TypeScript를 사용하는 경우 이 파일을 복사하여jsxJoin:

import { Fragment } from "react";

/**
 * Join together a set of JSX elements with a separator.
 *
 * @see https://stackoverflow.com/q/33577448/5506547
 */
function jsxJoin(components: JSX.Element[], separator: any) {
    // Just to be sure, remove falsy values so we can add conditionals to the components array
    const filtered = components.filter(Boolean);
    return filtered.length === 0
        ? null
        : (filtered.reduce(
              (acc, curr, i) =>
                  acc.length
                      ? [
                            ...acc,
                            // Wrap the separator in a fragment to avoid `missing key` issues
                            <Fragment key={i}>{separator}</Fragment>,
                            curr
                        ]
                      : [curr],
              []
          ) as JSX.Element[]);
}

export { jsxJoin };
// typescript
export function joinArray<T, S>(array: Array<T>, separator: S): Array<T | S> {
  return array.reduce<(T | S)[]>((p, c, idx) => {
    if (idx === 0) return [c];
    else return [...p, separator, c];
  }, []);
}
// javascript
export function joinArray(array, separator) {
    return array.reduce((p, c, idx) => {
        if (idx === 0)
            return [c];
        else
            return [...p, separator, c];
    }, []);
}
// example
console.log(joinArray(["1", "2", "3"], 2));
// -> ["1", 2, "2", 2, "3"]
// example
// privacyViews -> JSX.Element[]
const privacyViews = joinArray(
  privacys.value.map(({ key, name }) => {
    return (
      <button onClick={() => clickPrivacy(key!)} class={Style.privacyBtn}>
        {name}
      </button>
    );
  }),
  <span class={Style.privacyBtn}>、</span>
);

모든 케이스에 대응합니다.

const items = []
    if(x1) {
       items.push(<span>text1</span>)
    }
    if(x2) {
       items.push(<span>text3</span>)
    }
    if(x3) {
       items.push(<span>text3</span>)
    }
    
    
    return <div>
        <>{items.reduce((result, item) => result.length > 0 ? [...result, ', ', item] : [item], [])}</>
    </div>

언급URL : https://stackoverflow.com/questions/33577448/is-there-a-way-to-do-array-join-in-react

반응형