React에서 변수와 문자열 연결 방법이 있습니까?

React의 중괄호 표기법을 통합하는 방법이 있습니까? href 태그 있습니까? 상태에 다음 값이 있다고 가정하십시오.

{this.state.id}

태그의 다음 HTML 속성 :

href="#demo1"
id="demo1"

내가 추가 할 수있는 방법이 있습니까 idHTML 속성에 상태를 다음과 같은 것을 얻을

href={"#demo + {this.state.id}"}

어느 것이 산출 될까요?

#demo1


답변

당신은 거의 정확하며 몇 가지 따옴표를 잘못 배치했습니다. 모든 것을 정규 따옴표로 묶으면 문자 그대로 문자열 #demo + {this.state.id}이 표시됩니다. 변수와 문자열 리터럴을 표시해야합니다. 내부의 {}것은 인라인 JSX 표현식 이므로 다음을 수행 할 수 있습니다.

href={"#demo" + this.state.id}

문자열 리터럴을 사용 #demo하여 값으로 연결합니다 this.state.id. 그런 다음 모든 문자열에 적용 할 수 있습니다. 이걸 고려하세요:

var text = "world";

이:

{"Hello " + text + " Andrew"}

결과는 다음과 같습니다.

Hello world Andrew 

또한 `(backticks)와 (interpolated expression) 과 함께 ES6 문자열 보간 / 템플리트 리터럴 을 사용할 수 있습니다 ${expr}.

href={`#demo${this.state.id}`}

이것은 기본적으로의 값을 대체하여 this.state.id에 연결합니다 #demo. 다음을 수행하는 것과 같습니다 "#demo" + this.state.id..


답변

소품 / 변수를 연결하는 가장 좋은 방법 :

var sample = "test";
var result = `this is just a ${sample}`;
//this is just a test

답변

exampleData =

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

예 1 =


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

예 2 =

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

두 번째 예를 권장합니다. 빠릅니다.