[英]How to use onClick in imported .map() react.js
好的,所以我有兩個文件Test.js和Test2.js
Test.js:
import React from 'react';
const hello = ['hello', 'hi', 'sup'];
export const helloWorld = hello.map(helloCode => {
return (
<button onClick={this.handleClick}>{helloCode}</button>
);
});
Test2.js:
import React from 'react';
import { helloWorld } from './Test';
export class RealTest extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('clicked');
}
render() {
return (
<div>
{helloWorld}
</div>
);
}
};
我不知道如何獲取helloWorld來訪問onClick函數,我嘗試創建一個道具,嘗試綁定它,但是除非它在Test2.js中,否則我無法使其工作,但是我需要它來在它自己的單獨文件中。 謝謝您的幫助。
@Adam建議傳遞上下文,但我認為它更像是React來傳遞道具。
export const HelloWorld = props => hello.map(helloCode => {
return (
<button
key={helloCode} // <--- make sure to add a unique key
onClick={props.handleClick}
>
{helloCode}
</button>
);
});
然后渲染:
<div>
<HelloWorld handleClick={this.handleClick} />
</div>
通過變量helloWorld
訪問的JSX數組不知道要在其自身文件中使用的上下文(例如this
)是什么(因此,不能使用this.handleClick
)。
最簡單的方法是使其成為一個函數,以便您可以傳遞正確的上下文:
import React from 'react';
const hello = ['hello', 'hi', 'sup'];
export const helloWorld = (context) => hello.map(helloCode => {
return (
<button onClick={context.handleClick}>{helloCode}</button>
);
});
然后在您的render方法中,傳遞上下文:
render() {
return (
<div>
{helloWorld(this)}
</div>
);
}
const hello = ['hello', 'hi', 'sup']; const HelloWorld = (props) => <div>{hello.map(name =>(<button onClick={() => props.handleClick(name)}>{name}</button>))}</div> class RealTest extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(name) { console.log('clicked for name ', name); } render() { return ( <div> <HelloWorld handleClick={this.handleClick} /> </div> ); } }; ReactDOM.render( <RealTest/>, document.getElementById('root') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.