首页 文章

如何在JavaScript函数中访问ReactJS属性

提问于
浏览
1

我的ReactJS属性中有一个(可能是复杂的)JSON结构 - this.props.fieldsCollection . 我想在JavaScript函数中获取此对象,以便我可以遍历它并在React-Component中设置带有值的下拉列表 .

我无法在JS函数中获得值 .

function getPropertyValue() {
    $(document).ready(function() {
        var data = this.props.fieldsCollection; //gives "undefined"
    });
}

我希望在“var data”中返回集合,以及迭代它的方法 . 我是Web开发人员的新手(所以请善待我的简单问题:)))

---------------------解决方案感谢您的回答---这是我的其他所做的-----------

它只是在ReactJS的render方法中设置全局JavaScript变量中的值 .

例如,

var fieldsCollection; // global JS variable


module.exports = React.createClass({
    displayName: 'SidebarHeader',
    render: function () {
        return (
            fieldsCollection = this.props.fieldsCollection, // setting the global variable value first when render is called
               <div className="sidebar-header">
                 <div  className="multi-select-field">

//incomplete React.createClass code …

function someJavaScriptFunction() {
    var index, length = fieldsCollection.length;
    for(index = 0; index<length; index++)
    {
        console.log(fieldsCollection.models[index].id); // testing code to iterate through the fieldsCollection ..
    }
}

2 回答

  • 1

    您可以在全局范围上创建变量,然后在其中一个组件的事件中设置它的值 .

    例如:

    var varToRead = 0
    
    var Hello = React.createClass({
        getInitialState : function (){
            varToRead += 1;
            return null
        },
        render: function () {
            return <div>Hello {this.props.name}</div>;
        }
    });
    
    ReactDOM.render(
        <Hello name="World" />,
        document.getElementById('container')
    );
    
    $(document).ready(function(){
        console.log(varToRead)        
    })
    

    这里 varToRead 是您想要读取的变量 . 我们在 getInitialState 上设置它的值,它作为组件事件的一个例子 .

    您可以看到我使用getInitialState示例的组件规范和生命周期:https://facebook.github.io/react/docs/component-specs.html

    正在运行的示例如下:https://jsfiddle.net/c8x07p0s/

  • 0

    这是一个例子 .

    import React from 'react';
    
    import JDropMenu from './common/jDropMenu';
    
    let DropDownMenuSty = {
    	fontSize: '1.2em',
    	padding: '2px 2px 0 0',
    	position: 'relative',
    	right: '0',
    	top: '0'
    };
    
    let options = [
    	{ value: 'new', label: 'New' },
    	{ value: 'edit', label: 'Edit' },
    	{ type: 'seperator', key: '100'},
    	{ value: 'moveUp', label: 'Move up' },
    	{ value: 'moveDown', label: 'Move down' },
    	{ type: 'seperator', key: '101'},
    	{ value: 'rename', label: 'Rename' },
    	{ type: 'seperator', key: '102'},
    	{ value: 'remove', label: 'Remove' }
    ];
    
    class DropDownMenuRender extends React.Component {
    	render() {
    		let optionLabel = this.state.option.label;
    		let optionValue = this.state.option.value;
    		return (
    			<div>
    				<div id='DropDownMenuSty' style={DropDownMenuSty}>
    					<JDropMenu options={options} onChange={this.onSelect} />
    				</div>
    				Label: {optionLabel}
    Value: {optionValue} </div> ) } } export default class DropDownMenu extends DropDownMenuRender { constructor() { super(); this.state = {option: {}}; } onSelect = (option) => { this.setState({option: option}); } }
    import React from 'react';
    
    let DropdownSty = { position: 'relative' };
    
    let DropdownControlSty = {
    	position: 'relative',
    	overflow: 'hidden',
    	background: 'transparent',
    	boxSizing: 'border-box',
    	cursor: 'default',
    	outline: 'none',
    	padding: '5px 5px',
    	textAlign: 'right',
    	transition: 'all 200ms ease',
    	width: '100%'
    };
    
    let DropdownMenuSty = {
    	backgroundColor: '#261a3b',
    	boxShadow: '0 1px 0 rgba(0, 0, 0, 0.06)',
    	boxSizing: 'border-box',
    	fontSize: '.9em',
    	lineHeight: '150%',
    	marginTop: '-1px',
    	maxHeight: '300px',
    	overflowY: 'auto',
    	padding: '8px 12px',
    	position: 'absolute',
    	right: '0',
    	top: '100%',
    	zIndex: '10'
    };
    
    let DropdownSeperatorSty = {
    	backgroundColor: '#000000',
    	height: '3px',
    	margin: '3px 0',
    	width: '100%'
    };
    
    let DropdownNoresultsSty = {
    	boxSizing: 'border-box',
    	color: '#ccc',
    	cursor: 'default',
    	display: 'block',
    	padding: '8px 10px'
    };
    
    let DropdownOptionSty = {
    	boxSizing: 'border-box',
    	color: '#EEFFEE',
    	cursor: 'pointer',
    	display: 'block'
    };
    
    class JDropMenuRender extends React.Component {
    	render() {
    		let items = this.props.options.map((option) => {
    			if (option.type == 'seperator') {
    				return (<div style={DropdownSeperatorSty} key={option.key}></div>)
    			} else {
    				return (
    					<div
    						key={option.value}
    						style={DropdownOptionSty}
    						onMouseDown={this.setValue.bind(this, option)}
    						onClick={this.setValue.bind(this, option)}
    					>{option.label}</div>
    				)
    			}
    		});
    
    		let value = (<i className="fa fa-bars fa-lg"></i>);
    		let menu = this.state.isOpen ? <div style={DropdownMenuSty}>{items}</div> : null;
    
    		return (
    			<div style={DropdownSty}>
    				<div style={DropdownControlSty} onMouseDown={this.handleMouseDown} onTouchEnd={this.handleMouseDown}>
    					{value}
    				</div>
    	      {menu}
    			</div>
    		)
    	}
    }
    
    export default class JDropMenu extends JDropMenuRender {
    	constructor() {
    	  super();
    		this.state = { isOpen: false, selected: {} };
    	}
    	handleMouseDown = (event) => {
    		if (event.type == 'mousedown' && event.button !== 0) return;
    		event.stopPropagation();
    		event.preventDefault();
    		this.setState({ isOpen: !this.state.isOpen })
    	}
    	setValue = (option) => {
    		this.props.onChange(option);
    		this.setState({isOpen: false});
    	}
    }
    

相关问题