我想在我的頭中使用鏈接滾動到我的應用程序的不同部分與scrollIntoView。標題是App的一個孩子。我得到一個TypeError,說我試圖保存id的變量是未定義的。有人可以幫助我確定我做錯了什麼嗎?我想我可能不得不使用ComponentDidMount,但我不知道如何去做,如果這是修復。我將不得不這樣做我的所有標題鏈接。如何在React中使用scrollIntoView?
//錯誤 bundle.js:152遺漏的類型錯誤:在App.getScrollLocations無法讀取屬性 'scrollIntoView' 空 的(bundle.js:152) 在的onClick(bundle.js:19957) 的對象.ReactErrorUtils.invokeGuardedCallback(bundle.js:4660) 在executeDispatch(bundle.js:4460) 在Object.executeDispatchesInOrder(bundle.js:4483) 在executeDispatchesAndRelease(bundle.js:3913) 在executeDispatchesAndReleaseTopLevel(bundle.js :3924) at Array.forEach() at forEachAccumulated(bundle.js:4760) at Obje ct.processEventQueue(bundle.js:4129) ///////
//應用
class App extends Component {
constructor(props) {
super(props);
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
this.getScrollLocations = this.getScrollLocations.bind(this);
this.state = {
open: false,
projects: Service,
selectedProject: Service[0]
}
}
closeModal(event) {
this.setState({open: false});
}
openModal(project) {
this.setState({
open: true,
selectedProject: project
});
}
///////////// scroll function //////////////
getScrollLocations() {
const whatIDo = document.getElementById('.whatIdo');
console.log(whatIDo)
whatIDo.scrollIntoView();
}
render() {
const show = {
display: 'block'
};
const hide = {
display: 'none'
};
return (
<div>
<div style={this.state.open === false ? hide : show}>
<Modal
value={this.state.open}
closeModal={this.closeModal}
project={this.state.selectedProject}
/>
</div>
<Header
//////////// FUNCTION PASSED TO HEADER ///////////////
getScrollLocations={this.getScrollLocations}
/>
<Intro />
/////////////// ELEMENT I AM TARGETING /////////////////
<WhatIDo id="whatIDo" />
<WhoIAm />
<Gallery
value={this.state.open}
projects={this.state.projects}
openModal={this.openModal}
/>
<Contact />
<Footer />
</div>
);
}
}
//部首
const header = (props) => {
console.log(props);
return (
<div className="header">
<div className="header-name">
XXXXXXX XXXXXXX
</div>
<div className="header-links">
<ul>
<li>Intro</li>
<li
///////////// FUNCTION CALL ON CLICK /////////////////
onClick={() => props.getScrollLocations()}
>What I do</li>
<li>Who I am</li>
<li>My Work</li>
<li>Contact</li>
</ul>
</div>
</div>
)
}
好吧,我會試試這個。謝謝。 – jcs1977
什麼是這個文件:import scrollIntoViewIfNeeded從'scroll-into-view-if-needed';? – jcs1977
這是一個模塊,用於檢測瀏覽器頁面是否在本機支持ScrollIntoView,如果瀏覽器不支持scrollIntoview,那麼該模塊不執行任何操作,如果用戶瀏覽器不支持scrollIntoView,則該模塊提供一個polyfill來啓用特徵。 這個模塊的更多文檔: https://www.npmjs.com/package/scroll-into-view-if-needed 爲ScrollIntoView 瀏覽器支持: http://caniuse.com/#feat=scrollintoview –