Bootstrap 팝오버 내에서 React 구성 요소 렌더링
-
21-12-2019 - |
문제
콘텐츠 속성/매개변수에 부트스트랩 팝오버 UI 구성요소를 사용하여 팝오버가 있는 이미지 세트가 있습니다. ReactJS MusicList 구성요소를 추가하고 싶지만 구문이나 가능한지 여부를 알 수 없습니다.
var MusicList = React.createClass({
render : function(){
return(<ul><li>Here</li></ul>);
}
});
var PopoverImage = React.createClass({
componentDidMount:function(){
$("#"+this.getDOMNode().id).attr('data-component','<span>here</span>');
$("#"+this.getDOMNode().id).popover({
html:true,
content:
});
},
render:function(){
return(
<img href="#" id={this.props.friend.uid+'_popover'} data-html={true} className="smallImage" src={this.props.friend.pic_small} rel="popover" data-original-title={this.props.friend.name} />
);
}
});
해결책
부트스트랩을 사용하면 팝오버 내에서 동적 구성 요소를 쉽게 렌더링할 수 없습니다.표시하려는 팝오버가 정적인 경우 간단히 React의 renderComponentToString
구성요소를 가져와 콜백을 통해 HTML 문자열을 반환합니다.
var html = React.renderComponentToString(<MusicList />);
$(this.getDOMNode()).popover({
html: true,
content: html
});
그러나 구성 요소에 상호 작용이 있는 경우 React는 이벤트 핸들러를 연결하거나 사용자 정의 수명 주기 메서드를 실행할 기회가 없기 때문에 해당 전략은 작동하지 않습니다.실제로 Bootstrap은 팝오버 콘텐츠를 동적으로 만드는 데 적합한 후크를 제공하지 않습니다.
즉, Bootstrap을 패치하여 이 작업을 수행하는 것이 가능합니다.저는 동적 팝오버 콘텐츠가 포함된 라이브 데모를 만들었습니다.
http://jsfiddle.net/spicyj/q6hj7/
현재 시간은 매초 업데이트되는 React 구성 요소에 의해 팝오버 내에서 렌더링됩니다.
이 팝오버는 어떻게 만들어졌나요?
패치했어요 부트스트랩 팝오버 setContent
방법 HTML이나 텍스트 문자열 외에 React 구성 요소를 사용합니다.jQuery를 사용하는 대신 html
또는 text
내가 사용하는 방법 React.renderComponent
:
// Patch Bootstrap popover to take a React component instead of a
// plain HTML string
$.extend($.fn.popover.Constructor.DEFAULTS, {react: false});
var oldSetContent = $.fn.popover.Constructor.prototype.setContent;
$.fn.popover.Constructor.prototype.setContent = function() {
if (!this.options.react) {
return oldSetContent.call(this);
}
var $tip = this.tip();
var title = this.getTitle();
var content = this.getContent();
$tip.removeClass('fade top bottom left right in');
// If we've already rendered, there's no need to render again
if (!$tip.find('.popover-content').html()) {
// Render title, if any
var $title = $tip.find('.popover-title');
if (title) {
React.renderComponent(title, $title[0]);
} else {
$title.hide();
}
React.renderComponent(content, $tip.find('.popover-content')[0]);
}
};
이제 글쓰기가 가능해졌습니다
$(this.getDOMNode()).popover({
react: true,
content: <MusicList />
});
당신의 componentDidMount
메서드를 사용하여 올바르게 렌더링하도록 하세요.연결된 JSFiddle을 보면 범용 <BsPopover />
래퍼 구성 요소가 DOM에서 제거되면 팝오버 구성 요소를 적절하게 정리하는 것을 포함하여 모든 Bootstrap 호출을 처리하는 래퍼를 만들었습니다.
다른 팁
React-Bootstrap이라는 새로운 라이브러리가 빠른 개발을 겪고 있습니다.
"Nofollow"> https://reactobootstrap.github.io/components.html#popovers <./ a>
이 모듈을 포함하는 경우 변수에 저장할 수있는 자체 구성 요소를 렌더링 함수에서 사용할 수있는 자체 구성 요소를 만들 수 있습니다.
react.eRender (positionerinstance, mountNode);
showmoredetails : 함수 (obj, columns) {
var popOver = (
<Popover>
<table>
{
columns.map(col =>
<tr>
<td style={{textAlign:'right', padding:5}}>
{col.label}:
</td>
<td style={{padding:5}}>
{obj[col.key]}
</td>
</tr>
)
}
</table>
</Popover>
);
return(
<OverlayTrigger trigger='click' rootClose placement='left' overlay={popOver}>
<div className="popover-more">more...</div>
</OverlayTrigger>
);
},
. 이 답변을 게시하고 테스트를 한 후에이 작업을 중심으로 한 후에, 나는 그것이 최적이 아니라는 것을 깨닫는다.
BootStrap 드롭 다운 메뉴 사용자가 그와 상호 작용하자마자 닫습니다. 이것은 원하는 행동이 아닐 수도 있습니다 (내 경우, DatePicker를 삽입하고 사용자는 새 날짜를 선택하기 위해 메뉴를 다시 열지 않고도 월을 변경할 수 없음).
나는 똑같은 문제를 가지고 있었고 나는 쉽고 대안적인 해결책을 생각해 냈습니다.
React-Bootstrap을 사용하고 싶지 않았습니다.
Bootstrap에 의해 상자 밖으로 제공된 드롭 다운 구성 요소는 거의 동일한 기능을 제공합니다. 이것은 표준 부트 스트랩 드롭 다운입니다.
<div class="dropdown">
<button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown trigger
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dLabel">
...
</ul>
</div>
.
여기에이를 깨지 않고 작동시키지 않고 작동하는 데 필요한 최소값이 있습니다.
에있는 반응 요소를 포함 할 수 있습니다.<div className="dropdown">
<button data-toggle="dropdown">
Dropdown trigger
</button>
<div className="dropdown-menu">
<myGreatReactIntervactiveComponent
value={this.props.value}
onChange={this.handleChange}
onClick={this.handleClick}
children={this.greatChildrenForMyGreatREactInteractiveComponent}
/>
</div>
</div>
.
래퍼 DIV의 클래스 "드롭 다운"(ii) 트리거의 데이터 전환 속성 "드롭 다운"과 같은 클래스 "드롭 다운"이 필요합니다 (원하는 HTML 요소로 트리거를 변경할 수 있음). (iii) 드롭 다운의 클래스 "드롭 다운 메뉴"(원하는 HTML 요소로 변경할 수도 있고 부트 스트랩에 의해 제안한 "UL"요소를 고정시키지 않아도됩니다.
Popover와 비교하여 몇 가지 기능을 풉니 다 (자신의 전환을 정의 할 수 없으며, 왼쪽 또는 오른쪽에 표시 할 수는 없지만 아래에만 표시 할 수 없지만 드롭 다운이지만 콘텐츠를 완전히 제어 할 수 있습니다. 드롭 다운 / 팝 오버의
Popover (예 : '페이지')가 포함 된 구성 요소의 렌더링 기능에서 렌더링 함수가 될 수있는 반응 구성 요소가 포함되도록 해결하는 또 다른 방법은 스타일로 Div 내부에 배치 "디스플레이 : 없음;...에 "그래서 공간이 표시되지 않고 공간을 차지하지 않으므로 ID를 제공합니다.'popovercontent'.그런 다음 Popover Set 내용을 초기화 할 때 : document.getElementById ( "popovercontent").부트 스트랩 4에서는 적어도 요소를 콘텐츠로 가져옵니다.
이 방법으로 부트 스트랩 코드를 수정할 필요가 없으므로 유지 보수 / 업데이트가 쉽습니다.