반응 성분을 다른 반응 성분으로 전달하여 첫 번째 성분의 내용을 포함시키는 방법은 무엇입니까?
한 구성 요소를 다른 반응 구성 요소로 전달하는 방법이 있습니까? 모델 반응 구성 요소를 만들고 다른 반응 구성 요소를 전달하여 해당 내용을 변환하고 싶습니다.
편집 : 여기 내가하려는 일을 보여주는 reactJS 코드 펜이 있습니다. http://codepen.io/aallbrig/pen/bEhjo
HTML
<div id="my-component">
<p>Hi!</p>
</div>
반응 JS
/**@jsx React.DOM*/
var BasicTransclusion = React.createClass({
render: function() {
// Below 'Added title' should be the child content of <p>Hi!</p>
return (
<div>
<p> Added title </p>
{this.props.children}
</div>
)
}
});
React.renderComponent(BasicTransclusion(), document.getElementById('my-component'));
this.props.children
구성 요소에 포함 된 모든 자식을 렌더링 하는 데 사용할 수 있습니다 .
const Wrap = props => <div>{props.children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
여기에 더 자세한 답변을 제공했습니다.
런타임 래퍼 :
가장 관용적 인 방법입니다.
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = () => <div>Hello</div>;
const WrappedApp = () => (
<Wrapper>
<App/>
</Wrapper>
);
참고 children
"특별한 소품"반작용에, 위의 예제는 문법 설탕과에 (거의) 동일합니다<Wrapper children={<App/>}/>
초기화 래퍼 / HOC
HOC ( Higher Order Component)를 사용할 수 있습니다 . 최근에 공식 문서 에 추가되었습니다 .
// Signature may look fancy but it's just
// a function that takes a component and returns a new component
const wrapHOC = (WrappedComponent) => (props) => (
<div>
<div>header</div>
<div><WrappedComponent {...props}/></div>
<div>footer</div>
</div>
)
const App = () => <div>Hello</div>;
const WrappedApp = wrapHOC(App);
래퍼 구성 요소는 shouldComponentUpdate를 사용하여 렌더링을 한 단계 앞당길 수 있기 때문에 성능이 약간 저하 될 수 있습니다. 컴포넌트가 PureComponent를 확장하더라도
이 공지 사항 connect
돌아 오는의 런타임 래퍼로 사용하지만 쓸모 방지 할 수있게 때문에 HOC로 변경 재 - 렌더링 당신이 사용하는 경우 pure
(기본적으로 true입니다) 옵션을
React 컴포넌트를 작성하는 데 많은 비용이들 수 있으므로 렌더링 단계에서 HOC를 호출하면 안됩니다. 초기화시이 랩퍼를 호출해야합니다.
위와 같은 기능적 구성 요소를 사용할 때 HOC 버전은 상태 비 저장 기능성 구성 요소가 구현되지 않기 때문에 유용한 최적화를 제공하지 않습니다. shouldComponentUpdate
자세한 설명은 여기 : https://stackoverflow.com/a/31564812/82609
const ParentComponent = (props) => {
return(
{props.childComponent}
//...additional JSX...
)
}
//import component
import MyComponent from //...where ever
//place in var
const myComponent = <MyComponent />
//pass as prop
<ParentComponent childComponent={myComponent} />
Facebook은 상태 비 저장 구성 요소 사용을 권장합니다. 출처 : https://facebook.github.io/react/docs/reusable-components.html
이상적인 세계에서 대부분의 구성 요소는 상태 비 저장 기능이 될 것입니다. 앞으로는 불필요한 검사 및 메모리 할당을 피함으로써 이러한 구성 요소에 맞게 성능을 최적화 할 수 있기 때문입니다. 가능하면 권장되는 패턴입니다.
function Label(props){
return <span>{props.label}</span>;
}
function Hello(props){
return <div>{props.label}{props.name}</div>;
}
var hello = Hello({name:"Joe", label:Label({label:"I am "})});
ReactDOM.render(hello,mountNode);
React 내장 API를 선호합니다.
import React, {cloneElement, Component} from "react";
import PropTypes from "prop-types";
export class Test extends Component {
render() {
const {children, wrapper} = this.props;
return (
cloneElement(wrapper, {
...wrapper.props,
children
})
);
}
}
Test.propTypes = {
wrapper: PropTypes.element,
// ... other props
};
Test.defaultProps = {
wrapper: <div/>,
// ... other props
};
그런 다음 래퍼 div를 원하는 것으로 바꿀 수 있습니다.
<Test wrapper={<span className="LOL"/>}>
<div>child1</div>
<div>child2</div>
</Test>
일반 소품으로 전달할 수 있습니다. foo={<ComponentOne />}
예를 들면 다음과 같습니다.
const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
<div>
<div>Hola el mundo!</div>
<ComponentThree foo={<ComponentOne />} />
</div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>
You can pass in a component via. the props and render it with interpolation.
var DivWrapper = React.createClass({
render: function() {
return <div>{ this.props.child }</div>;
}
});
You would then pass in a prop
called child
, which would be a React component.
Late to the game, but here's a powerful HOC pattern for overriding a component by providing it as a prop. It's simple and elegant.
Suppose MyComponent
renders a fictional A
component but you want to allow for a custom override of A
, in this example B
, which wraps A
in a <div>...</div>
and also appends "!" to the text prop:
import A from 'fictional-tooltip';
const MyComponent = props => (
<props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };
const B = props => (
<div><A {...props} text={props.text + '!'}></div>
);
ReactDOM.render(<MyComponent A={B}/>);
Here is an example of a parent List react component and whos props contain a react element. In this case, just a single Link react component is passed in (as seen in the dom render).
class Link extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<p>{this.props.name}</p>
</div>
);
}
}
class List extends React.Component {
render(){
return(
<div>
{this.props.element}
{this.props.element}
</div>
);
}
}
ReactDOM.render(
<List element = {<Link name = "working"/>}/>,
document.getElementById('root')
);
Actually, your question is how to write a Higher Order Component (HOC). The main goal of using HOC is preventing copy-pasting. You can write your HOC as a purely functional component or as a class here is an example:
class Child extends Component {
render() {
return (
<div>
Child
</div>
);
}
}
If you want to write your parent component as a class-based component:
class Parent extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
If you want to write your parent as a functional component:
const Parent=props=>{
return(
<div>
{props.children}
</div>
)
}
'Programing' 카테고리의 다른 글
ModelState.AddModelError-속성이 아닌 오류를 어떻게 추가합니까? (0) | 2020.05.19 |
---|---|
`Optional.orElse ()`와`Optional.orElseGet ()`의 차이점 (0) | 2020.05.19 |
Tornado 사용시기, Twisted / Cyclone / GEvent / 기타 사용시기 (0) | 2020.05.19 |
Perl에서 나와 우리의 차이점은 무엇입니까? (0) | 2020.05.19 |
동적으로 삽입 된 iframe의 jQuery .ready (0) | 2020.05.19 |