您好我正在尝试在反应视图中使用bootstrap崩溃,但它无法正常工作。这很简单,但我不明白发生了什么。
return (<div>
<button className="btn" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="true" aria-controls="collapseExample">
ButtonClickthis!
</button>
<div className="collapse" id="collapseExample">
<div className="well">
...blablablacontent
</div>
</div>
</div>);
答案 0 :(得分:11)
Bootstrap不会为反应组件开箱即用,因为它在加载时解析DOM并附加事件侦听器等。您可以尝试react-bootstrap之类的内容或在componentDidMount生命周期内手动触发。
- David
答案 1 :(得分:3)
Bootstrap 5 不再需要 jQuery,这使得它更容易与 React 一起使用。例如,这里是使用 React useState、useEffect 钩子的 Bootstrap Collapse 组件:
FirebaseMessagingService
答案 2 :(得分:0)
我以前经历过这个。您需要做的就是手动触发componentDidMount中的事件。您可能还想在setState的回调中重新触发事件。
答案 3 :(得分:0)
值得一提的是:如果您在NPM / ES6环境中使用它 -
首先导入jquery并在加载bootstrap之前设置window.jQuery变量:
import $ from 'jquery';
window.jQuery = $;
import bootstrap from 'bootstrap';
至少我必须这样才能加载bootstrap。
一般来说,我认为最好使用已经转换到react-bootstrap项目中的React世界的组件。但在这种情况下(折叠),它尚未转换。
答案 4 :(得分:0)
如果你不想搞乱jQuery:
首先,为每个可折叠元素构建一个ref对象;还构建了一个函数来将.show
CSS类切换到相应的元素。
然后,在按钮onClick
中使用切换器功能。
class Collapse extends React.Component {
constructor(props) {
super(props)
this.refs = {}
// build ref object with collapsible elements ids
this.setRef = (element) => {
this.refs[element.id] = element
}
// toggle "show" CSS class using plain JS
this.collapseRef = (id) => {
if (this.refs) this.refs[id].classList.toggle('show')
}
}
render() {
return (
<div>
<button
type="button"
onClick={() => this.collapseRef('content1')}
>
Collapse!
</button>
<div
className="collapse"
// Use the `ref` callback to store a reference to the collapsible DOM element
ref={this.setRef}
id="content1"
>
Collapsible content
</div>
</div>
)
}
}
答案 5 :(得分:0)
使用npm安装模块
npm install react-bootstrap bootstrap
并导入您的组件
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
这对我有用