React.js 2-바인딩 방법:두 가지 수준의 깊은 경로에 valueLink
-
22-12-2019 - |
문제
나의 상태:
[
{type: "translateX", x: 10},
{type: "scaleX", x: 1.2}
]
내가 사용하는 두 방법은 바인딩을 도우미 과할 수 없습 제공하는 유효한 키 문자열 linkState
:
this.state.map(function(item, i) {
return <div><input valueLink={this.linkState( ??? )}></div>
}
면 좋을 것입 this.linkState
일부 허용 쿼리문 등 "0.type"
검색 "translateX"
내 예입니다.
어떤 방법?
내가 쓴 DeepLinkState mixin 는 대체 반응합니다.애드온.LinkedStateMixin.사용 예제:
this.state.map(function(item, i) {
return <div><input valueLink={this.linkState([i, "x"])}></div>
}
linkState("0.x")
또한 사용 가능한 구문입니다.
해결책
편집 :
나는 LinkedState
의 깊은 경로가 꽤 멋지게 그것을 구현하려고 노력했다.
코드 : https://gist.github.com/tungd/8367229
사용법 : http://jsfiddle.net/uhm6k/3/
문서가 명시되어 있으므로 LinkedState
는 onChange/setState
주위의 래퍼이며 간단한 경우를 의미합니다.항상 Full onChange/setState
를 작성하여 원하는 것을 얻을 수 있습니다.LinkedState
로 정말로 고정시키고 싶다면 비 믹스 버전을 사용할 수 있습니다 (예 :
getInitialState: function() {
return { values: [
{ type: "translateX", x: 10 },
{ type: "scaleX", x: 1.2 }
]}
},
handleTypeChange: function(i, value) {
this.state.values[i].type = value
this.setState({ values: this.state.values })
},
render: function() {
...
this.state.values.map(function(item, i) {
var typeLink = {
value: this.state.values[i].type,
requestChange: this.handleTypeChange.bind(null, i)
}
return <div><input valueLink={typeLink}/></div>
}, this)
...
}
.
여기에 JSFIDDLE : http://jsfiddle.net/srbgl//a>
다른 팁
Base Mixin이 사용자를 만족시키지 못하면 자신의 믹스를 구현할 수 있습니다.
이 mixin이 어떻게 구현되는지 확인하십시오 :
var LinkedStateMixin = {
/**
* Create a ReactLink that's linked to part of this component's state. The
* ReactLink will have the current value of this.state[key] and will call
* setState() when a change is requested.
*
* @param {string} key state key to update. Note: you may want to use keyOf()
* if you're using Google Closure Compiler advanced mode.
* @return {ReactLink} ReactLink instance linking to the state.
*/
linkState: function(key) {
return new ReactLink(
this.state[key],
ReactStateSetters.createStateKeySetter(this, key)
);
}
};
/**
* @param {*} value current value of the link
* @param {function} requestChange callback to request a change
*/
function ReactLink(value, requestChange) {
this.value = value;
this.requestChange = requestChange;
}
.
https://github.com/facebook/ 반응 / BLOB / FC73BF0A0ABF739A9A8E6B1A5197DAB113E76F27 / src / addons / link / linkedstatemixin.js https://github.com/facebook/react/blob. /fc73bf0a0abf739a9a8e6b1a5197dab113e76f27/src/addons/link/reactlink.js
위의 위의 linkState
기능을 쉽게 작성하려고 할 수 있습니다.
linkState: function(key,key2) {
return new ReactLink(
this.state[key][key2],
function(newValue) {
this.state[key][key2] = newValue;
}
);
}
.
ReactStateSetters.createStateKeySetter(this, key)
를 사용하지 않았습니다.
https://github.com/facebook/react/blob/fc73bf0a0abf739a9a8e6b1a5197dab113e76f27 /src/core/reactstateetters.js
소스 코드를 다시 보면이 메서드가 기능을 생성하고 기능을 작성하고 거의 캐싱 된 최적화가 거의없는 경우를 제외하고는 그렇게 할 수 없습니다.
function createStateKeySetter(component, key) {
// Partial state is allocated outside of the function closure so it can be
// reused with every call, avoiding memory allocation when this function
// is called.
var partialState = {};
return function stateKeySetter(value) {
partialState[key] = value;
component.setState(partialState);
};
}
.
당신은 당신이 자신만의 믹스를 작성하려고 노력해야합니다. 이는 상태에 복잡한 개체를 사용하고 개체 API를 통해 수정하려는 경우 매우 유용 할 수 있습니다.
가치 링크 addon을 사용하지 않고 해당합니다.
여기에 demo : http://wingspan.github.io/Wingspan 형식 / 예 / Form-Twins /
비밀 소스는 하나의 onchange 함수 만 정의하는 것입니다 :
onChange: function (path, /* more paths,*/ value) {
// clone the prior state
// traverse the tree by the paths and assign the value
this.setState(nextState);
}
.
다음과 같이 사용하십시오 :
<input
value={this.state['forms']['0']['firstName']}
onChange={_.partial(this.onChange, 'forms', '0', 'firstName')} />
.
모든 곳에서 전달 해야하는 (value, onChange)
쌍이 많으면리스 링크와 비슷한 추상화를 정의하는 것이 의미가 있지만 개인적으로리스 링크를 사용하지 않고 꽤 멀리 멀리 있습니다.
나의 동료와 나는 최근에 소스를 열었습니다.깊게 중첩 된 상태.우리는이 접근법을 많이 활용합니다.gitHub 페이지의 링크 된 상태로 더 많은 예제 데모를 볼 수 있습니다.
I http://blog.sendsonar.com/2015/08/04/anguly-like-deep-path-data-bindings-in-react/
그러나 기본적으로 부모와 깊은 경로의 '상태'를 수락하는 새로운 구성 요소를 만들어 추가 코드를 작성할 필요가 없습니다.
<MagicInput binding={[this, 'account.owner.email']} />
.
JSFiddle도 있습니다. 그래서 당신이 그것을 가지고 놀 수 있습니다
여기에는 방법을 설명하는 튜토리얼을 처리할 것입니다.
상태 및 형태에서 반응,제 3 부:을 처리하는 복잡한 국가
TL;박사:
0)사용하지 않는 기준 링크입니다.사 이.
1)귀하는 다음과 같이:
collection : [
{type: "translateX", x: 10},
{type: "scaleX", x: 1.2}
]
2)링크 collection
:
var collectionLink = Link.state( this, 'collection' );
3)반복하는 링크를 통해 그것의 요소:
collectionLink.map(function( itemLink, i ) {
return <div><input valueLink={itemLink}></div>
})